<?php

namespace Tests\Feature\BranchIsolation;

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

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

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

        $role = Role::create(['name'=>'phase8-final-controller','display_name'=>'Phase 8 Final Controller']);
        $role->permissions()->attach(Permission::whereIn('name', [
            'accounts.view','accounts.manage','cash-closing.view',
        ])->pluck('id'));

        $user = User::factory()->create([
            'username'=>'phase8_final_primary_only','status'=>'active','primary_branch_id'=>$branchA->id,
        ]);
        $user->roles()->attach($role->id);
        $this->assertSame([], $user->branches()->pluck('branches.id')->all());

        $accountA = FinancialAccount::create([
            'branch_id'=>$branchA->id,'name'=>'Phase 8 Final Cash A','account_type'=>'cash',
            'opening_balance'=>'100000.00','current_balance'=>'100000.00','status'=>'active',
        ]);
        $accountB = FinancialAccount::create([
            'branch_id'=>$branchB->id,'name'=>'Phase 8 Final Cash B','account_type'=>'cash',
            'opening_balance'=>'100000.00','current_balance'=>'100000.00','status'=>'active',
        ]);

        $this->actingAs($user)->get(route('accounts.index'))
            ->assertOk()->assertSee($accountA->name)->assertDontSee($accountB->name)
            ->assertSee($branchA->name)->assertDontSee($branchB->name);

        $this->actingAs($user)->get(route('accounts.create'))
            ->assertOk()->assertSee($branchA->name)->assertDontSee($branchB->name);

        $this->actingAs($user)->get(route('cash-closing.index', [
            'branch_id'=>$branchA->id,'date'=>'2026-08-13',
        ]))->assertOk()->assertSee($branchA->name)->assertDontSee($branchB->name);

        $this->actingAs($user)->get(route('cash-closing.index', [
            'branch_id'=>$branchB->id,'date'=>'2026-08-13',
        ]))->assertForbidden();
    }
}
