<?php

declare(strict_types=1);

namespace App\Framework\Search\ValueObjects;

use InvalidArgumentException;

/**
 * Value Object for search entity types
 * Defines what kind of entity is being indexed (user, product, article, etc.)
 */
final readonly class EntityType
{
    public function __construct(public string $value)
    {
        if (empty(trim($value))) {
            throw new InvalidArgumentException('Entity type cannot be empty');
        }

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

        // Ensure entity type follows naming conventions (lowercase, underscores)
        if (! preg_match('/^[a-z][a-z0-9_]*$/', $value)) {
            throw new InvalidArgumentException('Entity type must start with lowercase letter and contain only lowercase letters, numbers, and underscores');
        }
    }

    // Common entity types for convenience
    public static function user(): self
    {
        return new self('user');
    }

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

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

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

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

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

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

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

    /**
     * Get the index name for this entity type
     * Useful for search engines that use separate indices per type
     */
    public function getIndexName(): string
    {
        return "search_{$this->value}";
    }

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