<?php

namespace App\Support;

enum RestoreRunStatus: string
{
    case Draft = 'draft';
    case Scoped = 'scoped';
    case Checked = 'checked';
    case Previewed = 'previewed';
    case Pending = 'pending';
    case Queued = 'queued';
    case Running = 'running';
    case Completed = 'completed';
    case Partial = 'partial';
    case Failed = 'failed';
    case Cancelled = 'cancelled';

    // Legacy / compatibility statuses (existing housekeeping semantics)
    case Aborted = 'aborted';
    case CompletedWithErrors = 'completed_with_errors';

    public static function fromString(?string $value): ?self
    {
        if ($value === null) {
            return null;
        }

        $normalized = strtolower(trim($value));
        $normalized = str_replace([' ', '-'], '_', $normalized);

        return self::tryFrom($normalized);
    }

    public function canTransitionTo(self $next): bool
    {
        if ($this === $next) {
            return true;
        }

        return match ($this) {
            self::Draft => in_array($next, [self::Scoped, self::Cancelled], true),
            self::Scoped => in_array($next, [self::Checked, self::Cancelled], true),
            self::Checked => in_array($next, [self::Previewed, self::Cancelled], true),
            self::Previewed => in_array($next, [self::Queued, self::Cancelled], true),
            self::Pending => in_array($next, [self::Queued, self::Running, self::Cancelled], true),
            self::Queued => in_array($next, [self::Running, self::Cancelled], true),
            self::Running => in_array($next, [self::Completed, self::Partial, self::Failed, self::Cancelled], true),
            self::Completed,
            self::Partial,
            self::Failed,
            self::Cancelled,
            self::Aborted,
            self::CompletedWithErrors => false,
        };
    }

    public function isDeletable(): bool
    {
        return in_array($this, [
            self::Draft,
            self::Scoped,
            self::Checked,
            self::Previewed,
            self::Completed,
            self::Partial,
            self::Failed,
            self::Cancelled,
            self::Aborted,
            self::CompletedWithErrors,
        ], true);
    }
}
