<?php

use App\Models\Branch;
use App\Models\Region;
use App\Models\User;
use App\Services\BranchAccessService;

beforeEach(function () {
    $this->service = app(BranchAccessService::class);
});

test('super_admin has unrestricted access (null)', function () {
    $user = User::factory()->superAdmin()->create();

    expect($this->service->accessibleBranchIds($user))->toBeNull();
});

test('region_admin sees exactly their own region\'s branches', function () {
    $regionA = Region::factory()->create();
    $regionB = Region::factory()->create();
    $branchesA = Branch::factory()->count(3)->create(['region_id' => $regionA->id]);
    Branch::factory()->count(2)->create(['region_id' => $regionB->id]);

    $user = User::factory()->regionAdmin()->create(['region_id' => $regionA->id]);

    $result = $this->service->accessibleBranchIds($user);

    expect($result)->toEqualCanonicalizing($branchesA->pluck('id')->all());
});

test('branch_admin and data_clerk see only their own branch', function () {
    $branch = Branch::factory()->create();
    Branch::factory()->create();

    $branchAdmin = User::factory()->branchAdmin()->create(['branch_id' => $branch->id]);
    $dataClerk = User::factory()->dataClerk()->create(['branch_id' => $branch->id]);

    expect($this->service->accessibleBranchIds($branchAdmin))->toEqual([$branch->id]);
    expect($this->service->accessibleBranchIds($dataClerk))->toEqual([$branch->id]);
});

test('branch-scoped viewer sees only their own branch', function () {
    $branch = Branch::factory()->create();

    $viewer = User::factory()->branchViewer()->create(['branch_id' => $branch->id]);

    expect($this->service->accessibleBranchIds($viewer))->toEqual([$branch->id]);
});

test('region-scoped viewer sees their region\'s branches', function () {
    $region = Region::factory()->create();
    $branches = Branch::factory()->count(2)->create(['region_id' => $region->id]);

    $viewer = User::factory()->regionViewer()->create(['region_id' => $region->id]);

    expect($this->service->accessibleBranchIds($viewer))->toEqualCanonicalizing($branches->pluck('id')->all());
});
