<?php

use App\Models\AdminSite;
use App\Models\AdminUser;
use App\Support\AdminAuthProfile;
use App\Support\SitePlatformRole;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

uses(RefreshDatabase::class);

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

test('site admin dashboard returns site overview for operator with dashboard permission', function (): void {
    $super = AdminUser::query()->create([
        'username' => 'super_site_dash',
        'name' => 'Super',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);
    grantSuperAdminRole($super);

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

    $create = $this->withHeader('Authorization', 'Bearer '.$token)
        ->postJson('/api/v1/admin/integration-sites', [
            'code' => 'site-dash',
            'name' => 'Site Dash',
            'admin_account' => [
                'username' => 'site_dash_admin',
                'nickname' => 'Site Dash Admin',
                'password' => 'secret-strong',
            ],
        ])
        ->assertCreated();

    $siteId = (int) $create->json('data.id');
    $operator = AdminUser::query()->where('username', 'site_dash_admin')->firstOrFail();
    $roleId = SitePlatformRole::id();

    expect((int) DB::table('admin_user_site_roles')
        ->where('admin_user_id', $operator->id)
        ->where('site_id', $siteId)
        ->where('role_id', $roleId)
        ->count())->toBe(1);

    expect(SitePlatformRole::userHasSiteAdminRole($operator))->toBeTrue();
    expect(AdminAuthProfile::fromAdmin($operator)['site']['code'] ?? null)->toBe('site-dash');

    $operatorToken = $operator->createToken('test', ['*'], now()->addDay())->plainTextToken;
    app('auth')->forgetGuards();

    $this->withHeader('Authorization', 'Bearer '.$operatorToken)
        ->getJson('/api/v1/admin/auth/me')
        ->assertOk()
        ->assertJsonPath('data.admin.id', $operator->id)
        ->assertJsonPath('data.admin.site.code', 'site-dash')
        ->assertJsonPath('data.admin.agent', null);

    $this->withHeader('Authorization', 'Bearer '.$operatorToken)
        ->getJson('/api/v1/admin/dashboard')
        ->assertOk()
        ->assertJsonPath('data.site_overview.admin_site_id', $siteId)
        ->assertJsonPath('data.site_overview.site_code', 'site-dash')
        ->assertJsonPath('data.agent_overview', null);
});
