<?php

use App\Services\Ticket\RiskPoolService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('risk pool lua acquire script returns structured status and pool counters', function (): void {
    $service = app(RiskPoolService::class);
    $method = new ReflectionMethod($service, 'acquireLua');
    $method->setAccessible(true);

    $lua = (string) $method->invoke($service);

    expect($lua)->toContain("return {'OK'")
        ->and($lua)->toContain('INVALID_ARGUMENT')
        ->and($lua)->toContain('POOL_NOT_INITIALIZED')
        ->and($lua)->toContain('VERSION_CONFLICT')
        ->and($lua)->toContain('INSUFFICIENT_CAP')
        ->and($lua)->toContain('remaining')
        ->and($lua)->toContain('locked')
        ->and($lua)->toContain('version')
        ->and($lua)->toContain("redis.call('EXPIRE', KEYS[1], tonumber(ARGV[3]))");
});

test('risk pool lua init overwrite and release scripts refresh redis ttl', function (): void {
    $service = app(RiskPoolService::class);

    $initMethod = new ReflectionMethod($service, 'initLua');
    $initMethod->setAccessible(true);
    $overwriteMethod = new ReflectionMethod($service, 'overwriteStateLua');
    $overwriteMethod->setAccessible(true);
    $releaseMethod = new ReflectionMethod($service, 'releaseLua');
    $releaseMethod->setAccessible(true);

    $initLua = (string) $initMethod->invoke($service);
    $overwriteLua = (string) $overwriteMethod->invoke($service);
    $releaseLua = (string) $releaseMethod->invoke($service);

    expect($initLua)->toContain("redis.call('EXPIRE', KEYS[1], tonumber(ARGV[4]))")
        ->and($overwriteLua)->toContain("redis.call('EXPIRE', KEYS[1], tonumber(ARGV[5]))")
        ->and($releaseLua)->toContain("redis.call('EXPIRE', KEYS[1], tonumber(ARGV[2]))");
});
