<?php

declare(strict_types=1);

namespace App\Framework\Database\TypeCaster;

use App\Framework\Core\ValueObjects\Hash;
use InvalidArgumentException;

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

        if (is_string($value)) {
            return Hash::fromString($value);
        }

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

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

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

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

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