<?php

declare(strict_types=1);

namespace App\Framework\Http;

use App\Framework\Filesystem\ValueObjects\FilePath;

/**
 * Production MIME type detector using PHP's mime_content_type()
 *
 * Detects MIME types from actual file content, returns MimeType enum if known
 * or CustomMimeType for unknown types
 */
final readonly class FilesystemMimeTypeDetector implements MimeTypeDetector
{
    public function detect(FilePath $filePath): MimeTypeInterface
    {
        if (!$filePath->exists()) {
            throw new \RuntimeException("File does not exist: {$filePath}");
        }

        $mimeTypeString = mime_content_type($filePath->toString());

        if ($mimeTypeString === false) {
            throw new \RuntimeException("Could not detect MIME type for: {$filePath}");
        }

        // Try to map to known MimeType enum
        $mimeType = MimeType::tryFromString($mimeTypeString);

        // If not found in enum, create CustomMimeType
        return $mimeType ?? CustomMimeType::fromString($mimeTypeString);
    }
}
