<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents\Polling;

/**
 * Value Object representing a unique poll identifier.
 */
final readonly class PollId
{
    private function __construct(
        public string $value
    ) {
        if (empty($value)) {
            throw new \InvalidArgumentException('Poll ID cannot be empty');
        }
    }

    /**
     * Create from string value.
     */
    public static function fromString(string $value): self
    {
        return new self($value);
    }

    /**
     * Generate for closure poll.
     */
    public static function forClosure(string $key, ?string $componentId = null): self
    {
        if ($componentId !== null) {
            return new self("closure.{$componentId}.{$key}");
        }

        return new self("closure.{$key}." . bin2hex(random_bytes(4)));
    }

    /**
     * Generate for attribute poll.
     */
    public static function forAttribute(string $className, string $methodName): self
    {
        return new self("attribute.{$className}::{$methodName}");
    }

    /**
     * Check if this is a closure poll.
     */
    public function isClosure(): bool
    {
        return str_starts_with($this->value, 'closure.');
    }

    /**
     * Check if this is an attribute poll.
     */
    public function isAttribute(): bool
    {
        return str_starts_with($this->value, 'attribute.');
    }

    /**
     * Check equality with another PollId.
     */
    public function equals(self $other): bool
    {
        return $this->value === $other->value;
    }

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