<?php

namespace Tests\Feature\CreditScore;

use App\Models\Role;
use App\Models\User;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CreditScoreProductionPermissionMigrationTest extends TestCase
{
    use RefreshDatabase;

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

    public function test_credit_score_permissions_exist_and_expected_system_roles_receive_them(): void
    {
        $permissions = ['credit-score.view', 'credit-score.history', 'credit-score.recalculate'];

        foreach ($permissions as $permission) {
            $this->assertDatabaseHas('permissions', [
                'name' => $permission,
                'guard_name' => 'web',
            ]);
        }

        foreach (['branch-administrator', 'branch-manager', 'loan-officer', 'loan-inspector'] as $roleName) {
            $role = Role::where('name', $roleName)->firstOrFail();
            foreach ($permissions as $permission) {
                $this->assertTrue($role->hasPermissionTo($permission), $roleName.' is missing '.$permission);
            }
        }

        foreach (['cashier', 'accountant'] as $roleName) {
            $role = Role::where('name', $roleName)->firstOrFail();
            foreach ($permissions as $permission) {
                $this->assertFalse($role->hasPermissionTo($permission), $roleName.' unexpectedly has '.$permission);
            }
        }
    }

    public function test_permissions_resolve_through_existing_role_assignments(): void
    {
        $role = Role::where('name', 'loan-inspector')->firstOrFail();
        $user = User::factory()->create(['status' => 'active']);
        $user->roles()->attach($role->id);

        $this->assertTrue($user->fresh()->can('credit-score.view'));
        $this->assertTrue($user->fresh()->can('credit-score.history'));
        $this->assertTrue($user->fresh()->can('credit-score.recalculate'));
    }
}
