<?php

namespace Tests\Feature\BranchIsolation;

use App\Models\Branch;
use App\Models\Business;
use App\Models\Customer;
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 Phase8LoanWorkflowScopeTest extends TestCase
{
    use RefreshDatabase;

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

    public function test_primary_only_user_keeps_adjustment_top_up_and_write_off_queues_scoped_to_primary_branch(): void
    {
        $business = Business::firstOrFail();
        $branchA = Branch::create(['business_id' => $business->id, 'name' => 'Phase 8 Loan Workflow A', 'status' => 'active']);
        $branchB = Branch::create(['business_id' => $business->id, 'name' => 'Phase 8 Loan Workflow B', 'status' => 'active']);

        $role = Role::create(['name' => 'phase8-loan-workflow', 'display_name' => 'Phase 8 Loan Workflow']);
        $role->permissions()->attach(Permission::whereIn('name', [
            'loans.adjustments.view',
            'loans.top-up.view',
            'loans.writeoff.view',
        ])->pluck('id'));

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

        $product = $this->product($business);
        $loanA = $this->loan($branchA, $product, 'LN-P8-WORKFLOW-A', 'CUS-P8-WORKFLOW-A');
        $loanB = $this->loan($branchB, $product, 'LN-P8-WORKFLOW-B', 'CUS-P8-WORKFLOW-B');

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

        $this->actingAs($user)
            ->get(route('loan-adjustments.index'))
            ->assertOk()
            ->assertSee($loanA->loan_number)
            ->assertDontSee($loanB->loan_number);

        $this->actingAs($user)
            ->get(route('loan-top-ups.index'))
            ->assertOk()
            ->assertSee($loanA->loan_number)
            ->assertDontSee($loanB->loan_number);

        $this->actingAs($user)
            ->get(route('loan-write-offs.index'))
            ->assertOk()
            ->assertSee($loanA->loan_number)
            ->assertDontSee($loanB->loan_number);
    }

    private function product(Business $business): LoanProduct
    {
        return LoanProduct::create([
            'business_id' => $business->id,
            'name' => 'Phase 8 Workflow Product',
            'minimum_amount' => '1000.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',
        ]);
    }

    private function loan(Branch $branch, LoanProduct $product, string $loanNumber, string $customerNumber): Loan
    {
        $customer = Customer::factory()->create([
            'branch_id' => $branch->id,
            'customer_number' => $customerNumber,
        ]);

        return Loan::create([
            'branch_id' => $branch->id,
            'customer_id' => $customer->id,
            'loan_product_id' => $product->id,
            'sequence_number' => 1,
            'sequence_year' => 2026,
            'loan_number' => $loanNumber,
            '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' => '90000.00',
            'interest_outstanding' => '9000.00',
            'fees_outstanding' => '0.00',
            'penalties_outstanding' => '0.00',
            'total_outstanding' => '99000.00',
            'total_paid' => '11000.00',
            'late_payment_penalty_type' => 'none',
            'late_payment_penalty_value' => '0.000000',
            'purpose' => 'Phase 8 branch scope regression',
            'schedule_start_date' => '2026-08-01',
            'status' => 'active',
            'disbursed_at' => '2026-08-01 09:00:00',
            'activated_at' => '2026-08-01 09:00:00',
            'schedule_activated_at' => '2026-08-01 09:00:00',
        ]);
    }
}
