<?php

declare(strict_types=1);

namespace App\Framework\Search\ValueObjects;

use InvalidArgumentException;

/**
 * Value Object for search entity identifiers
 * Ensures entity IDs are valid and properly formatted
 */
final readonly class EntityId
{
    public function __construct(public string $value)
    {
        if (empty(trim($value))) {
            throw new InvalidArgumentException('Entity ID cannot be empty');
        }

        if (strlen($value) > 255) {
            throw new InvalidArgumentException('Entity ID cannot exceed 255 characters');
        }

        // Ensure ID is search-engine safe (no special characters that could break indexing)
        if (! preg_match('/^[a-zA-Z0-9._-]+$/', $value)) {
            throw new InvalidArgumentException('Entity ID must contain only alphanumeric characters, dots, underscores, and hyphens');
        }
    }

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

    public static function generate(): self
    {
        return new self(uniqid('entity_', true));
    }

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

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

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