<?php

declare(strict_types=1);

namespace App\Framework\Database\TypeCaster;

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

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

        if (is_int($value)) {
            return FileSize::fromBytes($value);
        }

        if (is_string($value) && is_numeric($value)) {
            return FileSize::fromBytes((int) $value);
        }

        throw new InvalidArgumentException('FileSize value must be an integer (bytes)');
    }

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

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

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

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