<?php

declare(strict_types=1);

namespace App\Application\Api;

use App\Framework\Attributes\Route;
use App\Framework\Http\Method;
use App\Framework\Http\Status;
use App\Framework\Meta\StaticPageMetaResolver;
use App\Framework\OpenApi\OpenApiContact;
use App\Framework\OpenApi\OpenApiGenerator;
use App\Framework\OpenApi\OpenApiInfo;
use App\Framework\OpenApi\OpenApiLicense;
use App\Framework\Router\ApiRoutes;
use App\Framework\Router\Result\JsonResult;
use App\Framework\Router\Result\ViewResult;

/**
 * Controller for serving API documentation
 */
final readonly class ApiDocsController
{
    public function __construct(
        private OpenApiGenerator $generator,
    ) {
    }

    #[Route(path: '/api/docs', method: Method::GET, name: ApiRoutes::DOCS)]
    public function showDocs(): ViewResult
    {
        return new ViewResult(
            'api/docs',
            new StaticPageMetaResolver(
                'API Documentation',
                'Interactive API documentation with Swagger UI'
            )(),
            [
                'title' => 'API Documentation',
            ]
        );
    }

    #[Route(path: '/api/docs/selfhosted', method: Method::GET, name: ApiRoutes::DOCS_SELFHOSTED)]
    public function showDocsSelhosted(): ViewResult
    {
        return new ViewResult(
            'api/docs-selfhosted',
            new StaticPageMetaResolver(
                'API Documentation (Self-hosted)',
                'Self-hosted API documentation with zero external dependencies'
            )(),
            [
                'title' => 'API Documentation (Self-hosted)',
            ]
        );
    }

    #[Route(path: '/api/openapi.json', method: Method::GET, name: ApiRoutes::OPENAPI_SPEC)]
    public function getOpenApiSpec(): JsonResult
    {
        $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',
            ),
        );

        $protocol = (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';

        $servers = [
            [
                'url' => "{$protocol}://{$host}",
                'description' => 'Current server',
            ],
        ];

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

        return new JsonResult($spec->toArray(), Status::OK);
    }
}
