<?php

namespace NoahVet\Reef\Command\OpenAPI;

use NoahVet\Reef\Command\OpenAPI\QueryParamDumpCommandInterface 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:query-param:dump
 */
#[AsCommand(
    name: 'reef:open-api:query-param:dump',
    description: 'Create api query param files.',
    hidden: false,
)]
class QueryParamDumpCommand 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['parameters'])) {
                    $parameters = $this->openAPITool->cleanParameters($content);
                    if (!empty($parameters)) {
                        $this->writeFile(
                            $this->resolvePath($this->openAPITool->cleanUri($uri), $httpMethod, 'parameter'),
                            $this->yamlDumper->dumpContent($parameters),
                        );
                    }
                }
            }
        }

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

        return Command::SUCCESS;
    }
}
