<?php

declare(strict_types=1);

namespace NoahVet\Reef\Domain\Validation\V2;

use Symfony\Component\Yaml\Yaml;

final class RequestPayloadValidator implements RequestPayloadValidatorInterface
{
    public function __construct(
        private readonly OpenApiValidatorInterface $validator,
    ) {
    }

    public function validate(string $requestPayloadContent, string $modelPath): bool
    {
        // Check the payload is correct

        $decodedRequestPayloadContent = \json_decode($requestPayloadContent, true);

        if (!\is_array($decodedRequestPayloadContent)) {
            throw new \InvalidArgumentException('The request payload content must be a valid JSON payload.');
        }

        // Check the model is correct

        $modelContent = Yaml::parseFile($modelPath);

        if (!\is_array($modelContent)) {
            throw new \InvalidArgumentException('The OpenAPI model must be parsed as an array.');
        }

        return $this->validator->validate($decodedRequestPayloadContent, $modelContent);
    }
}
