<?php

use App\Models\BulkOperationRun;
use App\Models\RestoreRun;
use App\Support\RunIdempotency;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('builds a deterministic 64 char sha256 idempotency key', function () {
    $keyA1 = RunIdempotency::buildKey(1, 'policy.capture_snapshot', 'abc', ['b' => 2, 'a' => 1]);
    $keyA2 = RunIdempotency::buildKey(1, 'policy.capture_snapshot', 'abc', ['a' => 1, 'b' => 2]);
    $keyB = RunIdempotency::buildKey(1, 'policy.capture_snapshot', 'def', ['a' => 1, 'b' => 2]);

    expect($keyA1)->toBe($keyA2)
        ->and($keyA1)->not->toBe($keyB)
        ->and($keyA1)->toMatch('/^[a-f0-9]{64}$/');
});

it('finds only active bulk operation runs by idempotency key', function () {
    $pending = BulkOperationRun::factory()->create([
        'idempotency_key' => RunIdempotency::buildKey(1, 'bulk.policy.capture_snapshot', 'abc'),
        'status' => 'pending',
    ]);

    $completed = BulkOperationRun::factory()->create([
        'tenant_id' => $pending->tenant_id,
        'user_id' => $pending->user_id,
        'idempotency_key' => $pending->idempotency_key,
        'status' => 'completed',
    ]);

    expect(RunIdempotency::findActiveBulkOperationRun($pending->tenant_id, $pending->idempotency_key))
        ->not->toBeNull()
        ->id->toBe($pending->id);

    expect(RunIdempotency::findActiveBulkOperationRun($pending->tenant_id, $completed->idempotency_key))
        ->id->toBe($pending->id);
});

it('finds only active restore runs by idempotency key', function () {
    $active = RestoreRun::factory()->create([
        'idempotency_key' => RunIdempotency::buildKey(1, 'restore.execute', 123),
        'status' => 'queued',
    ]);

    RestoreRun::factory()->create([
        'tenant_id' => $active->tenant_id,
        'backup_set_id' => $active->backup_set_id,
        'idempotency_key' => $active->idempotency_key,
        'status' => 'completed',
    ]);

    expect(RunIdempotency::findActiveRestoreRun($active->tenant_id, $active->idempotency_key))
        ->not->toBeNull()
        ->id->toBe($active->id);
});
