<?php

use App\Models\AdminUser;
use App\Support\PlatformSystemRoles;
use App\Support\SiteOperatorRoles;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    $this->artisan('lottery:admin-auth-sync')->assertExitCode(0);
});

function bindSiteOperator(AdminUser $user, string $roleSlug): void
{
    $siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
    $roleId = (int) DB::table('admin_roles')->where('slug', $roleSlug)->value('id');

    DB::table('admin_user_site_roles')->insert([
        'admin_user_id' => $user->id,
        'site_id' => $siteId,
        'role_id' => $roleId,
        'granted_at' => now(),
    ]);
}

test('auth me exposes site role specific account_kind for site operators', function (): void {
    PlatformSystemRoles::ensureAll();

    $finance = AdminUser::query()->create([
        'username' => 'site_finance_ops',
        'name' => 'Site Finance',
        'email' => null,
        'password' => 'secret-strong',
        'status' => 0,
    ]);
    bindSiteOperator($finance, SiteOperatorRoles::SLUG_SITE_FINANCE);

    $token = $finance->createToken('test', ['*'], now()->addDay())->plainTextToken;

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/auth/me')
        ->assertOk()
        ->assertJsonPath('data.admin.account_kind', 'site_finance')
        ->assertJsonPath('data.admin.site.code', fn ($code) => is_string($code) && $code !== '');

    expect($finance->fresh()->adminPermissionSlugs())
        ->toContain('prd.report.export')
        ->not->toContain('prd.agent.manage');
});

test('site cs auth me has cs account kind without report permissions', function (): void {
    PlatformSystemRoles::ensureAll();

    $cs = AdminUser::query()->create([
        'username' => 'site_cs_ops',
        'name' => 'Site CS',
        'email' => null,
        'password' => 'secret-strong',
        'status' => 0,
    ]);
    bindSiteOperator($cs, SiteOperatorRoles::SLUG_SITE_CS);

    $token = $cs->createToken('test', ['*'], now()->addDay())->plainTextToken;

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/auth/me')
        ->assertOk()
        ->assertJsonPath('data.admin.account_kind', 'site_cs');

    expect($cs->fresh()->adminPermissionSlugs())
        ->toContain('prd.users.view_cs')
        ->not->toContain('prd.report.view');
});
