<?php

use App\Models\AdminRole;
use App\Models\AdminUser;
use App\Lottery\ErrorCode;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Support\AdminPermissionBridge;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

function mintAdminTokenWithLegacySlugs(string $username, array $permissionSlugs): string
{
    $admin = AdminUser::query()->create([
        'username' => $username,
        'name' => 'Admin '.$username,
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);

    if ($permissionSlugs !== []) {
        $role = AdminRole::query()->create([
            'slug' => 'role_'.$username,
            'name' => 'Role '.$username,
        ]);

        $codes = [];
        foreach ($permissionSlugs as $slug) {
            $codes = array_merge($codes, AdminPermissionBridge::menuActionCodesForLegacy($slug));
        }
        $codes = array_values(array_unique($codes));

        $ids = DB::table('admin_menu_actions')
            ->whereIn('permission_code', $codes)
            ->where('status', 1)
            ->pluck('id')
            ->all();

        foreach ($ids as $mid) {
            DB::table('admin_role_menu_actions')->insert([
                'role_id' => $role->id,
                'menu_action_id' => (int) $mid,
            ]);
        }

        $siteId = AdminUser::defaultAdminSiteId();
        $admin->roles()->sync([
            (int) $role->id => [
                'site_id' => $siteId,
                'granted_at' => now(),
            ],
        ]);
    }

    return $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
}

test('admin api resource middleware allows login only resource for signed in admin', function (): void {
    $token = mintAdminTokenWithLegacySlugs('resource_ping', []);

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/ping')
        ->assertOk()
        ->assertJsonPath('code', ErrorCode::Success->value)
        ->assertJsonPath('data.scope', 'admin');
});

test('admin api resource middleware denies protected report resource without permission', function (): void {
    $token = mintAdminTokenWithLegacySlugs('resource_denied', []);

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/report-jobs')
        ->assertForbidden()
        ->assertJsonPath('code', ErrorCode::AdminForbidden->value);
});

test('admin api resource middleware allows protected report resource with mapped permission', function (): void {
    $token = mintAdminTokenWithLegacySlugs('resource_reporter', ['prd.report.view']);

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/report-jobs')
        ->assertOk()
        ->assertJsonPath('code', ErrorCode::Success->value)
        ->assertJsonPath('data.meta.total', 0);
});

test('admin api resource middleware denies wallet reconcile resource without permission', function (): void {
    $token = mintAdminTokenWithLegacySlugs('resource_wallet_denied', []);

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/wallet/transactions')
        ->assertForbidden()
        ->assertJsonPath('code', ErrorCode::AdminForbidden->value);
});

test('admin api resource middleware allows wallet reconcile resource with mapped permission', function (): void {
    $token = mintAdminTokenWithLegacySlugs('resource_wallet_viewer', ['prd.wallet_reconcile.view']);

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/wallet/transactions')
        ->assertOk()
        ->assertJsonPath('code', ErrorCode::Success->value)
        ->assertJsonPath('data.total', 0);
});

test('admin api resource middleware denies jackpot resource without permission', function (): void {
    $token = mintAdminTokenWithLegacySlugs('resource_jackpot_denied', []);

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/jackpot/pools')
        ->assertForbidden()
        ->assertJsonPath('code', ErrorCode::AdminForbidden->value);
});
