<?php

declare(strict_types=1);

namespace App\Framework\OpenApi;

/**
 * Generates Markdown documentation from OpenAPI specification
 */
final readonly class MarkdownGenerator
{
    public function generate(OpenApiSpec $spec): string
    {
        $markdown = "# {$spec->info->title}\n\n";
        $markdown .= "{$spec->info->description}\n\n";
        $markdown .= "**Version:** {$spec->info->version}\n\n";

        if (! empty($spec->servers)) {
            $markdown .= "## Servers\n\n";
            foreach ($spec->servers as $server) {
                $markdown .= "- **{$server['description']}**: `{$server['url']}`\n";
            }
            $markdown .= "\n";
        }

        $markdown .= "## Endpoints\n\n";

        foreach ($spec->paths as $path => $pathItem) {
            foreach ($pathItem as $method => $operation) {
                $markdown .= "### " . strtoupper($method) . " " . $path . "\n\n";
                $markdown .= $operation['summary'] . "\n\n";

                if (! empty($operation['description'])) {
                    $markdown .= $operation['description'] . "\n\n";
                }

                if (! empty($operation['parameters'])) {
                    $markdown .= "**Parameters:**\n\n";
                    foreach ($operation['parameters'] as $param) {
                        $required = $param['required'] ? '**required**' : 'optional';
                        $markdown .= "- `{$param['name']}` ({$param['in']}) - {$param['description']} ({$required})\n";
                    }
                    $markdown .= "\n";
                }

                if (! empty($operation['responses'])) {
                    $markdown .= "**Responses:**\n\n";
                    foreach ($operation['responses'] as $code => $response) {
                        $markdown .= "- `{$code}` - {$response['description']}\n";
                    }
                    $markdown .= "\n";
                }

                $markdown .= "---\n\n";
            }
        }

        return $markdown;
    }
}
