<?php

declare(strict_types=1);

namespace App\Framework\TypeCaster\Casters;

use App\Framework\Serializer\Json\JsonSerializer;
use App\Framework\TypeCaster\TypeCasterInterface;
use InvalidArgumentException;

final readonly class JsonCaster implements TypeCasterInterface
{
    public function __construct(
        private JsonSerializer $jsonSerializer
    ) {
    }

    public function fromString(string $value): mixed
    {
        if (empty($value)) {
            throw new InvalidArgumentException('JSON value cannot be empty');
        }

        try {
            return $this->jsonSerializer->deserialize($value);
        } catch (\Throwable $e) {
            throw new InvalidArgumentException('Invalid JSON: ' . $e->getMessage(), 0, $e);
        }
    }

    public function toString(mixed $value): string
    {
        try {
            return $this->jsonSerializer->serialize($value);
        } catch (\Throwable $e) {
            throw new InvalidArgumentException('Cannot serialize to JSON: ' . $e->getMessage(), 0, $e);
        }
    }

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

    public function getPattern(): string
    {
        // JSON pattern is complex - detailed validation happens in fromString()
        // Allow most characters but require at least some structure
        return '.+';
    }
}
