<?php

declare(strict_types=1);

namespace App\Support\OperationalControls;

use App\Models\OperationalControlActivation;
use App\Models\Workspace;

final class OperationalControlEvaluator
{
    public function __construct(
        private readonly OperationalControlCatalog $catalog,
    ) {}

    public function evaluate(string $controlKey, Workspace|int|null $workspace = null): OperationalControlDecision
    {
        $definition = $this->catalog->definition($controlKey);
        $workspaceId = $workspace instanceof Workspace
            ? (int) $workspace->getKey()
            : (is_int($workspace) ? $workspace : null);

        $globalActivation = OperationalControlActivation::query()
            ->forControl($definition['key'])
            ->forGlobalScope()
            ->notExpired()
            ->latest('id')
            ->first();

        if ($globalActivation instanceof OperationalControlActivation) {
            return OperationalControlDecision::paused(
                controlKey: $definition['key'],
                matchedScopeType: 'global',
                workspaceId: null,
                reasonText: $globalActivation->reason_text,
                expiresAt: $globalActivation->expires_at,
                sourceActivationId: (int) $globalActivation->getKey(),
            );
        }

        if ($workspaceId !== null) {
            $workspaceActivation = OperationalControlActivation::query()
                ->forControl($definition['key'])
                ->forWorkspaceScope($workspaceId)
                ->notExpired()
                ->latest('id')
                ->first();

            if ($workspaceActivation instanceof OperationalControlActivation) {
                return OperationalControlDecision::paused(
                    controlKey: $definition['key'],
                    matchedScopeType: 'workspace',
                    workspaceId: $workspaceId,
                    reasonText: $workspaceActivation->reason_text,
                    expiresAt: $workspaceActivation->expires_at,
                    sourceActivationId: (int) $workspaceActivation->getKey(),
                );
            }
        }

        return OperationalControlDecision::enabled($definition['key']);
    }
}