<?php

declare(strict_types=1);

namespace App\Framework\Database\TypeCaster;

use App\Domain\Common\ValueObject\PhoneNumber;

final class PhoneNumberCaster implements TypeCasterInterface
{
    public function supports(string $type): bool
    {
        return $type === PhoneNumber::class;
    }

    public function fromDatabase(mixed $value, array $options = []): ?PhoneNumber
    {
        if ($value === null || $value === '') {
            return null;
        }

        if (! is_string($value)) {
            throw new \InvalidArgumentException("Expected string for PhoneNumber, got " . gettype($value));
        }

        return PhoneNumber::from($value);
    }

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

        if (! $value instanceof PhoneNumber) {
            throw new \InvalidArgumentException("Expected PhoneNumber instance, got " . gettype($value));
        }

        return $value->getValue();
    }
}
