<?php

use App\Models\AdminRole;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

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

test('platform role sync persists agent role and user manage slugs', function (): void {
    $super = AdminUser::query()->create([
        'username' => 'persist_super',
        'name' => 'Super',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);
    grantSuperAdminRole($super);
    $token = $super->createToken('test', ['*'], now()->addDay())->plainTextToken;

    $role = AdminRole::query()->create([
        'slug' => 'agent_persist_test',
        'name' => 'Agent Persist Test',
    ]);

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->putJson('/api/v1/admin/admin-roles/'.$role->id.'/permissions', [
            'permission_slugs' => [
                'prd.agent.view',
                'prd.agent.manage',
                'prd.agent.role.view',
                'prd.agent.role.manage',
                'prd.agent.user.view',
                'prd.agent.user.manage',
            ],
        ])
        ->assertOk()
        ->assertJsonPath('data.permission_slugs', function ($slugs): bool {
            $list = is_array($slugs) ? $slugs : [];

            return in_array('prd.agent.role.manage', $list, true)
                && in_array('prd.agent.user.manage', $list, true);
        });
});

test('sync fails with clear error when agent manage menu actions are missing', function (): void {
    DB::table('admin_menu_actions')
        ->whereIn('permission_code', ['agent.role.manage', 'agent.user.manage'])
        ->delete();

    $role = AdminRole::query()->create([
        'slug' => 'agent_missing_catalog',
        'name' => 'Missing Catalog',
    ]);

    expect(fn () => $role->syncLegacyPermissionSlugs(['prd.agent.role.manage']))
        ->toThrow(\Illuminate\Validation\ValidationException::class);
});
