<?php

namespace App\Support\Badges\Domains;

use App\Support\Badges\BadgeCatalog;
use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeMapper;
use App\Support\Badges\BadgeSpec;
use App\Support\Badges\OperatorOutcomeTaxonomy;
use App\Support\OperationRunStatus;
use App\Support\Operations\OperationRunFreshnessState;

final class OperationRunStatusBadge implements BadgeMapper
{
    public function spec(mixed $value): BadgeSpec
    {
        $state = null;

        if (is_array($value)) {
            $status = BadgeCatalog::normalizeState($value['status'] ?? null);
            $freshnessState = BadgeCatalog::normalizeState($value['freshness_state'] ?? null);

            if (in_array($status, [OperationRunStatus::Queued->value, OperationRunStatus::Running->value], true)
                && $freshnessState === OperationRunFreshnessState::LikelyStale->value
            ) {
                return new BadgeSpec(
                    label: 'Likely stale',
                    color: 'warning',
                    icon: 'heroicon-m-exclamation-triangle',
                    iconColor: 'warning',
                );
            }

            $state = $status;
        }

        $state ??= BadgeCatalog::normalizeState($value);

        return match ($state) {
            OperationRunStatus::Queued->value => OperatorOutcomeTaxonomy::spec(BadgeDomain::OperationRunStatus, $state, 'heroicon-m-clock'),
            OperationRunStatus::Running->value => OperatorOutcomeTaxonomy::spec(BadgeDomain::OperationRunStatus, $state, 'heroicon-m-arrow-path'),
            OperationRunStatus::Completed->value => OperatorOutcomeTaxonomy::spec(BadgeDomain::OperationRunStatus, $state, 'heroicon-m-check-circle'),
            default => BadgeSpec::unknown(),
        };
    }
}
