<?php

namespace Tests\Feature\BranchIsolation;

use App\Models\Branch;
use App\Models\Business;
use App\Models\Customer;
use App\Models\FinancialAccount;
use App\Models\Loan;
use App\Models\LoanProduct;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class Phase8FinanceLoanControllerScopeTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(DatabaseSeeder::class);
    }

    public function test_primary_only_user_keeps_finance_and_loan_queue_scope_without_pivot_assignment(): void
    {
        $business = Business::firstOrFail();
        $branch = Branch::create(['business_id' => $business->id, 'name' => 'Phase 8 Finance Primary', 'status' => 'active']);

        $role = Role::create(['name' => 'phase8-finance-loan-scope', 'display_name' => 'Phase 8 Finance Loan Scope']);
        $role->permissions()->attach(Permission::whereIn('name', [
            'arrears.view', 'accounts.capital', 'loans.approve', 'loans.disburse',
        ])->pluck('id'));

        $user = User::factory()->create([
            'username' => 'phase8_finance_primary_only',
            'status' => 'active',
            'primary_branch_id' => $branch->id,
        ]);
        $user->roles()->attach($role->id);

        $account = FinancialAccount::create([
            'branch_id' => $branch->id,
            'name' => 'Phase 8 Finance Cash',
            'account_type' => 'cash',
            'opening_balance' => '100000.00',
            'current_balance' => '100000.00',
            'status' => 'active',
        ]);

        $customer = Customer::factory()->create([
            'branch_id' => $branch->id,
            'customer_number' => 'CUS-PHASE8-FINANCE',
        ]);
        $product = LoanProduct::create([
            'business_id' => $business->id,
            'name' => 'Phase 8 Finance Product',
            'minimum_amount' => '10000.00',
            'maximum_amount' => '500000.00',
            'duration' => 2,
            'duration_unit' => 'months',
            'interest_rate' => '10.000000',
            'interest_calculation_method' => 'flat',
            'repayment_frequency' => 'monthly',
            'grace_period_days' => 0,
            'late_payment_penalty_type' => 'none',
            'late_payment_penalty_value' => '0.000000',
            'processing_fee_type' => 'fixed',
            'processing_fee_value' => '0.000000',
            'insurance_fee_type' => 'fixed',
            'insurance_fee_value' => '0.000000',
            'other_charges' => '0.00',
            'collateral_required' => false,
            'guarantor_required' => false,
            'status' => 'active',
        ]);

        $overdue = $this->loan($branch, $customer, $product, 'LN-PHASE8-ARREARS', 'active', 8);
        $approval = $this->loan($branch, $customer, $product, 'LN-PHASE8-APPROVAL', 'under_review');
        $ready = $this->loan($branch, $customer, $product, 'LN-PHASE8-DISBURSE', 'ready_for_disbursement');

        $this->assertSame([], $user->branches()->pluck('branches.id')->all());

        $this->actingAs($user)->get(route('capital-injections.create'))
            ->assertOk()->assertSee($account->name);
        $this->actingAs($user)->get(route('arrears.index'))
            ->assertOk()->assertSee($overdue->loan_number);
        $this->actingAs($user)->get(route('loans.approvals.index'))
            ->assertOk()->assertSee($approval->loan_number);
        $this->actingAs($user)->get(route('loan-disbursements.index'))
            ->assertOk()->assertSee($ready->loan_number);
    }

    private function loan(Branch $branch, Customer $customer, LoanProduct $product, string $number, string $status, int $daysOverdue = 0): Loan
    {
        return Loan::create([
            'branch_id' => $branch->id,
            'customer_id' => $customer->id,
            'loan_product_id' => $product->id,
            'sequence_number' => random_int(100, 99999),
            'sequence_year' => (int) now()->format('Y'),
            'loan_number' => $number,
            'principal' => '100000.00',
            'interest' => '10000.00',
            'processing_fee' => '0.00',
            'insurance_fee' => '0.00',
            'other_charges' => '0.00',
            'fees' => '0.00',
            'total_repayment' => '110000.00',
            'principal_outstanding' => '100000.00',
            'interest_outstanding' => '10000.00',
            'fees_outstanding' => '0.00',
            'penalties_outstanding' => '0.00',
            'total_outstanding' => '110000.00',
            'total_paid' => '0.00',
            'overdue_principal' => $daysOverdue > 0 ? '10000.00' : '0.00',
            'overdue_interest' => '0.00',
            'overdue_fees' => '0.00',
            'total_overdue' => $daysOverdue > 0 ? '10000.00' : '0.00',
            'days_overdue' => $daysOverdue,
            'arrears_bucket' => $daysOverdue > 0 ? '8-30' : 'current',
            'purpose' => 'Phase 8 branch scope regression',
            'schedule_start_date' => now()->format('Y-m-d'),
            'status' => $status,
            'approved_at' => $status === 'ready_for_disbursement' ? now() : null,
            'disbursed_at' => $status === 'active' ? now() : null,
            'activated_at' => $status === 'active' ? now() : null,
            'schedule_activated_at' => $status === 'active' ? now() : null,
        ]);
    }
}
