<?php

namespace Tests\Feature;

use App\Models\Account;
use App\Models\Customer;
use App\Models\FinancialTransaction;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class AccountAndBtrcReportTest extends TestCase
{
    use RefreshDatabase;

    public function test_account_statement_combines_customer_collection_and_expense(): void
    {
        $admin = $this->admin(['accounts.view', 'accounts.manage']);
        $customer = Customer::create(['customer_code' => 'ACC-1', 'name' => 'Account Customer', 'contact_phone' => '01700000001', 'monthly_bill' => 500, 'status' => 1]);
        Account::create(['customer_id' => $customer->id, 'type' => 1, 'amount' => 500, 'description' => 'Monthly payment', 'entry_date' => now(), 'entry_by' => $admin->id]);
        FinancialTransaction::create(['type' => 'expense', 'category' => 'Office Rent', 'amount' => 200, 'payment_method' => 'cash', 'transaction_date' => now(), 'created_by' => $admin->id]);

        $this->actingAs($admin)->get(route('admin.accounts.statement'))->assertOk()->assertSee('Account Statement')->assertSee('Customer Payment')->assertSee('Office Rent')->assertSee('500.00')->assertSee('200.00');
        $this->actingAs($admin)->get(route('admin.accounts.statement.export'))->assertOk()->assertHeader('content-type', 'text/csv; charset=UTF-8');
    }

    public function test_btrc_report_filters_and_exports_subscriber_information(): void
    {
        $admin = $this->admin(['reports.view', 'reports.export']);
        Customer::create(['customer_code' => 'BTRC-1', 'name' => 'BTRC Subscriber', 'contact_phone' => '01700000002', 'national_id' => '1234567890', 'ip_address' => '10.0.0.2', 'zone' => 'Dhaka', 'monthly_bill' => 800, 'status' => 1, 'connection_date' => now()]);
        Customer::create(['customer_code' => 'OTHER-1', 'name' => 'Other Subscriber', 'contact_phone' => '01700000003', 'zone' => 'Chattogram', 'monthly_bill' => 700, 'status' => 1]);

        $this->actingAs($admin)->get(route('admin.reports.btrc', ['zone' => 'Dhaka']))->assertOk()->assertSee('BTRC Subscriber')->assertSee('1234567890')->assertSee('10.0.0.2')->assertDontSee('Other Subscriber');
        $this->actingAs($admin)->get(route('admin.reports.btrc.export', ['zone' => 'Dhaka']))->assertOk()->assertDownload();
    }

    private function admin(array $permissions): User
    {
        foreach ($permissions as $permission) {
            Permission::firstOrCreate(['name' => $permission]);
        }
        $role = Role::firstOrCreate(['name' => 'Admin']);
        $role->syncPermissions($permissions);
        $user = User::factory()->create();
        $user->assignRole($role);

        return $user;
    }
}
