<?php

declare(strict_types=1);

namespace App\Framework\OpenApi\Commands;

use App\Framework\Console\ConsoleCommand;
use App\Framework\Console\ConsoleInput;
use App\Framework\Console\ConsoleOutput;
use App\Framework\OpenApi\OpenApiContact;
use App\Framework\OpenApi\OpenApiGenerator;
use App\Framework\OpenApi\OpenApiInfo;
use App\Framework\OpenApi\OpenApiLicense;

/**
 * Console command to generate OpenAPI specification
 */
final readonly class GenerateOpenApiCommand
{
    public function __construct(
        private OpenApiGenerator $generator,
    ) {
    }

    #[ConsoleCommand('openapi:generate', 'Generate OpenAPI specification from controller attributes')]
    public function __invoke(ConsoleInput $input, ConsoleOutput $output): void
    {
        $output->writeLine('Generating OpenAPI specification...');

        $info = new OpenApiInfo(
            title: 'Michael Schiemer API',
            version: '1.0.0',
            description: 'API documentation for Michael Schiemer\'s custom PHP framework',
            contact: new OpenApiContact(
                name: 'Michael Schiemer',
                email: 'contact@michaelschiemer.dev',
            ),
            license: new OpenApiLicense(
                name: 'MIT',
                url: 'https://opensource.org/licenses/MIT',
            ),
        );

        $servers = [
            [
                'url' => 'http://localhost',
                'description' => 'Local development server (HTTP)',
            ],
            [
                'url' => 'https://localhost',
                'description' => 'Local development server (HTTPS)',
            ],
            [
                'url' => 'https://api.michaelschiemer.dev',
                'description' => 'Production server',
            ],
        ];

        $spec = $this->generator->generate($info, $servers);

        $outputFile = $input->getOption('output') ?? 'public/openapi.json';

        if (! is_dir(dirname($outputFile))) {
            mkdir(dirname($outputFile), 0755, true);
        }

        file_put_contents($outputFile, $spec->toJson());

        $output->writeSuccess("OpenAPI specification generated: {$outputFile}");
        $output->writeLine("View at: https://editor.swagger.io/?url=" . urlencode("https://localhost/{$outputFile}"));
    }
}
