<?php

declare(strict_types=1);

namespace App\Framework\Database\TypeCaster;

use App\Framework\DateTime\SystemClock;
use App\Framework\Ulid\Ulid;
use InvalidArgumentException;

final class UlidCaster implements TypeCasterInterface
{
    public function __construct(
        private readonly SystemClock $clock
    ) {
    }

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

        if (is_string($value)) {
            return Ulid::fromString($this->clock, $value);
        }

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

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

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

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

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