<?php

declare(strict_types=1);

namespace App\Framework\Logging\ValueObjects;

/**
 * Log Name Value Object
 * Validated log identifier
 */
final readonly class LogName
{
    public function __construct(
        public string $value
    ) {
        $this->validate();
    }

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

    private function validate(): void
    {
        if (empty($this->value)) {
            throw new \InvalidArgumentException('Log name cannot be empty');
        }

        // Only alphanumeric, underscore, and hyphen allowed
        if (!preg_match('/^[a-zA-Z0-9_-]+$/', $this->value)) {
            throw new \InvalidArgumentException(
                "Log name '{$this->value}' contains invalid characters. Only alphanumeric, underscore, and hyphen allowed."
            );
        }

        if (strlen($this->value) > 100) {
            throw new \InvalidArgumentException(
                "Log name '{$this->value}' is too long. Maximum 100 characters allowed."
            );
        }
    }

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

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

    /**
     * Extract subdirectory from log name
     * Format: {subdirectory}_{filename}
     */
    public function getSubdirectory(): ?string
    {
        $parts = explode('_', $this->value, 2);
        return count($parts) > 1 ? $parts[0] : null;
    }

    /**
     * Extract filename from log name
     * Format: {subdirectory}_{filename}
     */
    public function getFilename(): string
    {
        $parts = explode('_', $this->value, 2);
        return count($parts) > 1 ? $parts[1] : $this->value;
    }
}
