<?php

declare(strict_types=1);

namespace App\Framework\Database\TypeCaster;

use App\Framework\Http\MimeType;
use InvalidArgumentException;

final class MimeTypeCaster implements TypeCasterInterface
{
    public function fromDatabase(mixed $value, array $options = []): mixed
    {
        if ($value === null) {
            return null;
        }

        if (is_string($value)) {
            $mimeType = MimeType::fromString($value);
            if ($mimeType === null) {
                throw new InvalidArgumentException("Unknown MIME type: {$value}");
            }

            return $mimeType;
        }

        throw new InvalidArgumentException('MimeType value must be a string');
    }

    public function toDatabase(mixed $value, array $options = []): mixed
    {
        if ($value === null) {
            return null;
        }

        if ($value instanceof MimeType) {
            return $value->value;
        }

        throw new InvalidArgumentException('Value must be a MimeType instance');
    }

    public function supports(string $type): bool
    {
        return $type === MimeType::class;
    }
}
