<?php

namespace Tests\Feature\BranchIsolation;

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

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

    public function test_primary_only_user_keeps_expense_category_business_scope_without_pivot(): void
    {
        $business = Business::firstOrFail();
        $branch = Branch::create(['business_id'=>$business->id,'name'=>'Phase 8 Expense Categories','status'=>'active']);
        $existing = ExpenseCategory::where('business_id',$business->id)->firstOrFail();

        $role = Role::create(['name'=>'phase8-expense-category-manager','display_name'=>'Phase 8 Expense Category Manager']);
        $role->permissions()->attach(Permission::where('name','expenses.categories.manage')->firstOrFail()->id);

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

        $this->actingAs($user)->get(route('expense-categories.index'))
            ->assertOk()
            ->assertSee($business->name)
            ->assertSee($existing->name);

        $this->actingAs($user)->post(route('expense-categories.store'),[
            'business_id'=>$business->id,
            'name'=>'Phase 8 Primary Only Category',
            'code'=>'P8-PRIMARY',
            'description'=>'Primary-only branch access regression.',
        ])->assertRedirect();

        $this->assertDatabaseHas('expense_categories',[
            'business_id'=>$business->id,
            'name'=>'Phase 8 Primary Only Category',
            'code'=>'P8-PRIMARY',
            'status'=>'active',
        ]);
    }
}
