<?php

use App\Models\AuditLog;
use App\Models\AdminUser;
use App\Models\Draw;
use App\Lottery\DrawStatus;
use App\Lottery\DrawResultBatchStatus;
use App\Models\DrawResultBatch;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

function seedAdminApiResourceForAudit(string $code, string $routeName, string $moduleCode = 'draw'): void
{
    $now = now();
    DB::table('admin_api_resources')->updateOrInsert(
        ['code' => $code],
        [
            'module_code' => $moduleCode,
            'name' => $code,
            'http_method' => 'POST',
            'uri_pattern' => '/test',
            'route_name' => $routeName,
            'auth_mode' => 'permission_required',
            'is_audit_required' => true,
            'status' => 1,
            'updated_at' => $now,
            'created_at' => $now,
        ],
    );
}

test('admin api audit middleware records draw result batch publish with long target_type', function (): void {
    seedAdminApiResourceForAudit(
        'admin.draws.result-batches.publish',
        'api.v1.admin.draws.result-batches.publish',
    );

    $admin = AdminUser::query()->create([
        'username' => 'audit_publish_admin',
        'name' => 'Audit Publish',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);
    grantSuperAdminRole($admin);
    $token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;

    $draw = Draw::query()->create([
        'draw_no' => '20260525-100',
        'business_date' => '2026-05-25',
        'sequence_no' => 100,
        'status' => DrawStatus::Review->value,
        'settle_version' => 0,
    ]);

    $batch = DrawResultBatch::query()->create([
        'draw_id' => $draw->id,
        'result_version' => 1,
        'source_type' => 'rng',
        'status' => DrawResultBatchStatus::PendingReview->value,
    ]);

    $before = AuditLog::query()->count();

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->postJson("/api/v1/admin/draws/{$draw->id}/result-batches/{$batch->id}/publish")
        ->assertOk();

    expect(AuditLog::query()->count())->toBe($before + 1);

    /** @var AuditLog $row */
    $row = AuditLog::query()->latest('id')->first();
    expect($row->module_code)->toBe('draw')
        ->and($row->action_code)->toBe('publish')
        ->and($row->target_type)->toBe('admin.draws.result-batches.publish')
        ->and($row->target_id)->toBe((string) $batch->id);
});

test('admin api audit middleware records draw reopen', function (): void {
    $admin = AdminUser::query()->create([
        'username' => 'audit_reopen_admin',
        'name' => 'Audit Reopen',
        'email' => null,
        'password' => Hash::make('secret-strong'),
        'status' => 0,
    ]);
    grantSuperAdminRole($admin);
    $token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;

    $draw = Draw::query()->create([
        'draw_no' => '20260525-099',
        'business_date' => '2026-05-25',
        'sequence_no' => 99,
        'status' => DrawStatus::Cooldown->value,
        'cooling_end_time' => now()->addMinutes(10),
        'settle_version' => 0,
    ]);

    $before = AuditLog::query()->count();

    $this->withHeader('Authorization', 'Bearer '.$token)
        ->postJson("/api/v1/admin/draws/{$draw->id}/reopen", ['reason' => 'audit test'])
        ->assertOk();

    expect(AuditLog::query()->count())->toBe($before + 1);

    /** @var AuditLog $row */
    $row = AuditLog::query()->latest('id')->first();
    expect($row->module_code)->toBe('draw')
        ->and($row->action_code)->toBe('reopen')
        ->and($row->operator_id)->toBe($admin->id);
});
