<?php

declare(strict_types=1);

namespace App\Framework\Database\Migration;

final readonly class MigrationVersion
{
    public function __construct(
        public string $timestamp
    ) {
        if (! preg_match('/^\d{4}_\d{2}_\d{2}_\d{6}$/', $timestamp)) {
            throw new \InvalidArgumentException("Invalid migration timestamp format. Expected: YYYY_MM_DD_HHMMSS, got: {$timestamp}");
        }
    }

    public static function fromTimestamp(string $timestamp): self
    {
        return new self($timestamp);
    }

    public static function fromSequence(string $domain, int $sequence): self
    {
        // Convert to timestamp-like format for consistent sorting
        $timestamp = sprintf('%s_%03d_000000', $domain, $sequence);

        return new self($timestamp);
    }

    public function __toString(): string
    {
        return $this->timestamp;
    }

    public function toString(): string
    {
        return $this->timestamp;
    }

    public function compare(MigrationVersion $other): int
    {
        return $this->timestamp <=> $other->timestamp;
    }

    public function equals(MigrationVersion $other): bool
    {
        return $this->timestamp === $other->timestamp;
    }
}
