<?php

declare(strict_types=1);

namespace App\Support\RestoreSafety;

use InvalidArgumentException;

final readonly class RestoreSafetyAssessment
{
    public const string STATE_BLOCKED = 'blocked';

    public const string STATE_RISKY = 'risky';

    public const string STATE_READY_WITH_CAUTION = 'ready_with_caution';

    public const string STATE_READY = 'ready';

    public function __construct(
        public string $state,
        public ExecutionReadinessState $executionReadiness,
        public PreviewIntegrityState $previewIntegrity,
        public ChecksIntegrityState $checksIntegrity,
        public bool $positiveClaimSuppressed,
        public ?string $primaryIssueCode,
        public string $primaryNextAction,
        public string $summary,
    ) {
        if (! in_array($this->state, [
            self::STATE_BLOCKED,
            self::STATE_RISKY,
            self::STATE_READY_WITH_CAUTION,
            self::STATE_READY,
        ], true)) {
            throw new InvalidArgumentException('Unsupported restore safety assessment state.');
        }
    }

    public function canSignalReady(): bool
    {
        return in_array($this->state, [self::STATE_READY, self::STATE_READY_WITH_CAUTION], true);
    }

    /**
     * @return array{
     *     state: string,
     *     execution_readiness: array{
     *         allowed: bool,
     *         blocking_reasons: list<string>,
     *         mutation_scope: string,
     *         required_capability: string,
     *         display_summary: string
     *     },
     *     preview_integrity: array{
     *         state: string,
     *         freshness_policy: string,
     *         fingerprint: ?string,
     *         generated_at: ?string,
     *         invalidation_reasons: list<string>,
     *         rerun_required: bool,
     *         display_summary: string
     *     },
     *     checks_integrity: array{
     *         state: string,
     *         freshness_policy: string,
     *         fingerprint: ?string,
     *         ran_at: ?string,
     *         blocking_count: int,
     *         warning_count: int,
     *         invalidation_reasons: list<string>,
     *         rerun_required: bool,
     *         display_summary: string
     *     },
     *     positive_claim_suppressed: bool,
     *     primary_issue_code: ?string,
     *     primary_next_action: string,
     *     summary: string
     * }
     */
    public function toArray(): array
    {
        return [
            'state' => $this->state,
            'execution_readiness' => $this->executionReadiness->toArray(),
            'preview_integrity' => $this->previewIntegrity->toArray(),
            'checks_integrity' => $this->checksIntegrity->toArray(),
            'positive_claim_suppressed' => $this->positiveClaimSuppressed,
            'primary_issue_code' => $this->primaryIssueCode,
            'primary_next_action' => $this->primaryNextAction,
            'summary' => $this->summary,
        ];
    }
}
