<?php

declare(strict_types=1);

namespace App\Framework\Database\Notifications;

/**
 * Value Object für PostgreSQL LISTEN/NOTIFY Channel Namen
 */
final readonly class Channel
{
    private function __construct(
        public string $name
    ) {
        if (empty($name)) {
            throw new \InvalidArgumentException('Channel name cannot be empty');
        }

        // PostgreSQL channel names are limited to 63 characters
        if (strlen($name) > 63) {
            throw new \InvalidArgumentException('Channel name cannot exceed 63 characters');
        }

        // Channel names must be valid PostgreSQL identifiers
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $name)) {
            throw new \InvalidArgumentException(
                'Channel name must be a valid PostgreSQL identifier (alphanumeric and underscores, starting with letter or underscore)'
            );
        }
    }

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

    /**
     * Erstellt einen Channel-Namen aus einem Namespace und Event-Namen
     */
    public static function forEvent(string $namespace, string $eventName): self
    {
        return new self($namespace . '_' . $eventName);
    }

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

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