<?php

declare(strict_types=1);

namespace NoahVet\Reef\Decorator\Validation;

use NoahVet\Reef\Domain\Validation\OpenApiValidatorInterface;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Yaml\Yaml;

class RequestValidatorDecorator implements RequestValidatorDecoratorInterface
{
    public function __construct(
        private readonly OpenApiValidatorInterface $validator,
    ) {
    }

    public function validate(Request $request): array
    {
        $requestContent = $request->getContent();
        $decodedRequestContent = \json_decode($requestContent, true);
        $validContent = \is_array($decodedRequestContent);

        // Check if is json valid

        if (\is_string($requestContent) && false === $validContent) {
            throw new BadRequestException('Your payload is not json valid.');
        }

        $uri = $request->getRequestUri();
        $path = $this->getFilePath($uri, $request->getMethod());

        if (!\file_exists($path)) {
            // Change identifier as '1f092136-1edc-61f2-b4fb-4fd3866bfdaa' to 'id' because id is dynamic.
            $uri = \explode(
                '?',
                \preg_replace(
                    '/[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}/',
                    'id',
                    $request->getRequestUri(),
                ) ?? '',
            )[0];
            $path = $this->getFilePath($uri, $request->getMethod());
        }

        return $this->validator->validate(
            \json_decode($requestContent, true),
            Yaml::parseFile($path),
        );
    }

    private function getFilePath(string $uri, string $httpMethod): string
    {
        return \sprintf(
            '/var/www/doc/OpenAPI/Generated/Validation%s/%s/validation.yaml',
            $uri,
            \strtolower($httpMethod),
        );
    }
}
