<?php

declare(strict_types=1);

namespace App\Framework\Database\TypeCaster;

use App\Domain\ValueObjects\EmailAddress;
use InvalidArgumentException;

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

        if (is_string($value)) {
            return new EmailAddress($value);
        }

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

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

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

        throw new InvalidArgumentException('Value must be an EmailAddress instance');
    }

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