<?php

declare(strict_types=1);

namespace App\Framework\Http;

/**
 * Value Object for custom/unknown MIME types not in the MimeType enum
 */
final readonly class CustomMimeType implements MimeTypeInterface
{
    private string $primaryType;
    private string $subType;

    public function __construct(
        private string $value
    ) {
        $this->validate($value);
        [$this->primaryType, $this->subType] = $this->parse($value);
    }

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

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

    public function getPrimaryType(): string
    {
        return $this->primaryType;
    }

    public function getSubType(): string
    {
        return $this->subType;
    }

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

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

    private function validate(string $value): void
    {
        if (empty($value)) {
            throw new \InvalidArgumentException('MIME type cannot be empty');
        }

        if (!str_contains($value, '/')) {
            throw new \InvalidArgumentException("Invalid MIME type format: {$value}");
        }
    }

    /**
     * @return array{string, string}
     */
    private function parse(string $value): array
    {
        $parts = explode('/', $value, 2);
        return [$parts[0], $parts[1]];
    }
}
