<?php

declare(strict_types=1);

namespace App\Support\OperationalControls;

use Carbon\CarbonInterface;

final class OperationalControlDecision
{
    public function __construct(
        public readonly string $controlKey,
        public readonly string $effectiveState,
        public readonly string $matchedScopeType,
        public readonly ?int $workspaceId,
        public readonly ?string $reasonText,
        public readonly ?CarbonInterface $expiresAt,
        public readonly ?int $sourceActivationId,
    ) {}

    public static function enabled(string $controlKey): self
    {
        return new self(
            controlKey: $controlKey,
            effectiveState: 'enabled',
            matchedScopeType: 'none',
            workspaceId: null,
            reasonText: null,
            expiresAt: null,
            sourceActivationId: null,
        );
    }

    public static function paused(
        string $controlKey,
        string $matchedScopeType,
        ?int $workspaceId,
        ?string $reasonText,
        ?CarbonInterface $expiresAt,
        ?int $sourceActivationId,
    ): self {
        return new self(
            controlKey: $controlKey,
            effectiveState: 'paused',
            matchedScopeType: $matchedScopeType,
            workspaceId: $workspaceId,
            reasonText: $reasonText,
            expiresAt: $expiresAt,
            sourceActivationId: $sourceActivationId,
        );
    }

    public function isEnabled(): bool
    {
        return $this->effectiveState === 'enabled';
    }

    public function isPaused(): bool
    {
        return $this->effectiveState === 'paused';
    }

    public function hasWorkspaceScope(): bool
    {
        return $this->matchedScopeType === 'workspace' && $this->workspaceId !== null;
    }

    public function scopeLabel(): string
    {
        return match ($this->matchedScopeType) {
            'global' => 'Global',
            'workspace' => $this->workspaceId !== null ? 'Workspace #'.$this->workspaceId : 'Workspace',
            default => 'No active pause',
        };
    }

    public function expiresAtIso8601(): ?string
    {
        return $this->expiresAt?->toIso8601String();
    }
}