<?php

namespace NoahVet\Reef\Command\OpenAPI;

use NoahVet\Reef\Command\OpenAPI\ValidationParamDumpCommandInterface as SelfInterface;
use NoahVet\Reef\Domain\Tool\OpenAPIToolInterface;
use NoahVet\Reef\File\Dumper\Yaml\DumperInterface as YamlDumperInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * E.g.
 *
 * bin/console reef:open-api:validation:dump
 */
#[AsCommand(
    name: 'reef:open-api:validation:dump',
    description: 'Create api validation files.',
    hidden: false,
)]
class ValidationDumpCommand extends AbstractDumpCommand implements SelfInterface
{
    public function __construct(
        protected string $sourceFilePath,
        protected string $destinationDirectory,
        protected readonly OpenAPIToolInterface $openAPITool,
        protected readonly YamlDumperInterface $yamlDumper,
    ) {
        parent::__construct();
    }

    #[\Override]
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $openApiFile = $this->preExecute();

        /**
         * @var array<string, array<string, mixed>> $path
         */
        foreach ($openApiFile['paths'] as $uri => $path) {
            foreach ($path as $httpMethod => $content) {
                if (isset($content['requestBody'])) {
                    $schema = $content['requestBody']['content']['application/json']['schema'];
                    $yamlContent = $schema['properties'] ?? [];

                    if (isset($schema['required']) && \is_array($schema['required'])) {
                        $yamlContent['required'] = $schema['required'];
                    }
                    $this->writeFile(
                        $this->resolvePath($this->openAPITool->cleanUri($uri), $httpMethod, 'validation'),
                        $this->yamlDumper->dumpContent($yamlContent),
                    );
                }
            }
        }

        (new SymfonyStyle($input, $output))
            ->success(
                'The validation files have been correctly created!',
            )
        ;

        return Command::SUCCESS;
    }
}
