<?php

use App\Models\AdminUser;
use Database\Seeders\AdminRbacAndUserSeeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('admin dashboard api resource is bound after migrations without manual auth sync', function (): void {
    $this->seed(AdminRbacAndUserSeeder::class);

    $resourceId = (int) DB::table('admin_api_resources')
        ->where('code', 'admin.dashboard')
        ->value('id');

    expect($resourceId)->toBeGreaterThan(0);

    $bindingCount = DB::table('admin_api_resource_bindings')
        ->where('api_resource_id', $resourceId)
        ->count();

    expect($bindingCount)->toBeGreaterThan(0);

    $admin = AdminUser::query()->where('username', 'admin')->firstOrFail();
    $token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/dashboard')
        ->assertOk();
});

test('admin user without dashboard permission is forbidden on dashboard api', function (): void {
    $this->seed(AdminRbacAndUserSeeder::class);

    $admin = AdminUser::query()->create([
        'username' => 'no_dashboard',
        'name' => 'No Dashboard',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);

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

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->getJson('/api/v1/admin/dashboard')
        ->assertForbidden();
});
