<?php

declare(strict_types=1);

namespace App\Framework\Queue\ValueObjects;

use App\Framework\Ulid\UlidGenerator;

/**
 * Value Object representing a unique Worker identifier
 */
final readonly class WorkerId
{
    private function __construct(
        private string $value
    ) {
        if (empty($value)) {
            throw new \InvalidArgumentException('WorkerId cannot be empty');
        }
    }

    /**
     * Generate a new WorkerId
     */
    public static function generate(): self
    {
        $generator = new UlidGenerator();
        return new self('worker_' . $generator->generate());
    }

    /**
     * Create WorkerId for specific host and process
     */
    public static function forHost(string $hostname, int $pid): self
    {
        $generator = new UlidGenerator();
        // Create a deterministic ID based on hostname, PID, and ULID
        $identifier = sprintf('%s_%d_%s', $hostname, $pid, $generator->generate());

        return new self(substr(hash('sha256', $identifier), 0, 16));
    }

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

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

    /**
     * Get value (alias for toString)
     */
    public function getValue(): string
    {
        return $this->value;
    }

    /**
     * Check if two WorkerIds are equal
     */
    public function equals(self $other): bool
    {
        return $this->value === $other->value;
    }

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

    /**
     * JSON serialization
     */
    public function jsonSerialize(): string
    {
        return $this->value;
    }
}
