<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('reconciles stale covered runs from the console command', function (): void {
    [$user, $tenant] = createMinimalUserWithTenant(role: 'owner');

    $run = OperationRun::factory()->withUser($user)->forTenant($tenant)->create([
        'type' => 'policy.sync',
        'status' => OperationRunStatus::Queued->value,
        'outcome' => OperationRunOutcome::Pending->value,
        'created_at' => now()->subMinutes(20),
    ]);

    $this->artisan('tenantpilot:operation-runs:reconcile', [
        '--tenant' => [(string) $tenant->getKey()],
        '--type' => ['policy.sync'],
    ])
        ->assertSuccessful()
        ->expectsOutputToContain('reconciled 1');

    expect($run->fresh()->status)->toBe(OperationRunStatus::Completed->value)
        ->and(data_get($run->fresh()->context, 'reconciliation.reason_code'))->toBe('run.stale_queued');
});

it('supports dry-run mode without mutating runs', function (): void {
    [$user, $tenant] = createMinimalUserWithTenant(role: 'owner');

    $run = OperationRun::factory()->withUser($user)->forTenant($tenant)->create([
        'type' => 'policy.sync',
        'status' => OperationRunStatus::Queued->value,
        'outcome' => OperationRunOutcome::Pending->value,
        'created_at' => now()->subMinutes(20),
    ]);

    $this->artisan('tenantpilot:operation-runs:reconcile', [
        '--tenant' => [(string) $tenant->getKey()],
        '--type' => ['policy.sync'],
        '--dry-run' => true,
    ])->assertSuccessful();

    expect($run->fresh()->status)->toBe(OperationRunStatus::Queued->value)
        ->and($run->fresh()->outcome)->toBe(OperationRunOutcome::Pending->value);
});
