<?php

declare(strict_types=1);

namespace App\Framework\Queue\ValueObjects;

use App\Framework\Queue\Exceptions\InvalidDeadLetterQueueNameException;

/**
 * Value Object representing a Dead Letter Queue name
 */
final readonly class DeadLetterQueueName
{
    private const MAX_LENGTH = 100;
    private const MIN_LENGTH = 1;
    private const VALID_PATTERN = '/^[a-zA-Z0-9_\-\.]+$/';

    public function __construct(
        private string $name
    ) {
        $this->validate();
    }

    public static function fromString(string $name): self
    {
        return new self($name);
    }

    public static function default(): self
    {
        return new self('failed');
    }

    public static function forQueue(QueueName $queueName): self
    {
        return new self($queueName->toString() . '_failed');
    }

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

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

    private function validate(): void
    {
        if (strlen($this->name) < self::MIN_LENGTH) {
            throw InvalidDeadLetterQueueNameException::tooShort($this->name, self::MIN_LENGTH);
        }

        if (strlen($this->name) > self::MAX_LENGTH) {
            throw InvalidDeadLetterQueueNameException::tooLong($this->name, self::MAX_LENGTH);
        }

        if (! preg_match(self::VALID_PATTERN, $this->name)) {
            throw InvalidDeadLetterQueueNameException::invalidFormat($this->name, self::VALID_PATTERN);
        }
    }

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