<?php

declare(strict_types=1);

namespace App\Framework\Database\TypeCaster;

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

        if (is_string($value)) {
            $decoded = json_decode($value, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return $decoded;
            }

            throw new \InvalidArgumentException('Invalid JSON: ' . json_last_error_msg());
        }

        return $value;
    }

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

        return json_encode($value, JSON_THROW_ON_ERROR);
    }

    public function supports(string $type): bool
    {
        return $type === 'array' || $type === 'object';
    }
}
