<?php

declare(strict_types=1);

use App\Models\OperationalControlActivation;
use App\Models\Workspace;
use App\Support\OperationalControls\OperationalControlEvaluator;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('prefers an active global pause over a workspace pause', function (): void {
    $workspace = Workspace::factory()->create();

    OperationalControlActivation::factory()->workspaceScoped()->create([
        'control_key' => 'restore.execute',
        'workspace_id' => (int) $workspace->getKey(),
        'reason_text' => 'Workspace pause.',
    ]);

    $globalActivation = OperationalControlActivation::factory()->forGlobalScope()->create([
        'control_key' => 'restore.execute',
        'reason_text' => 'Global incident pause.',
    ]);

    $decision = app(OperationalControlEvaluator::class)->evaluate('restore.execute', $workspace);

    expect($decision->isPaused())->toBeTrue()
        ->and($decision->matchedScopeType)->toBe('global')
        ->and($decision->workspaceId)->toBeNull()
        ->and($decision->reasonText)->toBe('Global incident pause.')
        ->and($decision->sourceActivationId)->toBe((int) $globalActivation->getKey());
});

it('ignores expired global activations when resolving the effective state', function (): void {
    $workspace = Workspace::factory()->create();

    OperationalControlActivation::factory()->forGlobalScope()->create([
        'control_key' => 'restore.execute',
        'reason_text' => 'Expired global pause.',
        'expires_at' => now()->subMinute(),
    ]);

    $workspaceActivation = OperationalControlActivation::factory()->workspaceScoped()->create([
        'control_key' => 'restore.execute',
        'workspace_id' => (int) $workspace->getKey(),
        'reason_text' => 'Active workspace pause.',
    ]);

    $decision = app(OperationalControlEvaluator::class)->evaluate('restore.execute', $workspace);

    expect($decision->isPaused())->toBeTrue()
        ->and($decision->matchedScopeType)->toBe('workspace')
        ->and($decision->workspaceId)->toBe((int) $workspace->getKey())
        ->and($decision->reasonText)->toBe('Active workspace pause.')
        ->and($decision->sourceActivationId)->toBe((int) $workspaceActivation->getKey());
});