import { createOpenApiDocument, isSwaggerEnabled } from "@/lib/swagger";

export const dynamic = "force-dynamic";

const SWAGGER_UI_VERSION = "5.32.11";

function serializeForInlineScript(value: unknown) {
  return JSON.stringify(value)
    .replace(/</g, "\\u003c")
    .replace(/\u2028/g, "\\u2028")
    .replace(/\u2029/g, "\\u2029");
}

function page(specification: ReturnType<typeof createOpenApiDocument>) {
  const serializedSpecification = serializeForInlineScript(specification);

  return `<!doctype html>
<html lang="fr">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="Documentation interactive de l'API RH Connect" />
    <title>RH Connect — Swagger</title>
    <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@${SWAGGER_UI_VERSION}/swagger-ui.css" />
    <style>
      html { box-sizing: border-box; overflow-y: scroll; }
      *, *::before, *::after { box-sizing: inherit; }
      body { margin: 0; background: #f4f7fb; }
      .topbar { display: none; }
      .swagger-ui .info { margin: 32px 0 20px; }
      .swagger-ui .scheme-container { box-shadow: none; border: 1px solid #dbe3ef; }
    </style>
  </head>
  <body>
    <div id="swagger-ui"></div>
    <script src="https://unpkg.com/swagger-ui-dist@${SWAGGER_UI_VERSION}/swagger-ui-bundle.js" crossorigin></script>
    <script>
      window.onload = function () {
        window.ui = SwaggerUIBundle({
          spec: ${serializedSpecification},
          dom_id: "#swagger-ui",
          deepLinking: true,
          persistAuthorization: true,
          displayRequestDuration: true,
          filter: true,
          docExpansion: "none",
          tryItOutEnabled: false,
          withCredentials: true,
          presets: [SwaggerUIBundle.presets.apis],
        });
      };
    </script>
  </body>
</html>`;
}

export async function GET(request: Request) {
  if (!isSwaggerEnabled()) {
    return new Response("Documentation API désactivée.", {
      status: 404,
      headers: { "Content-Type": "text/plain; charset=utf-8" },
    });
  }

  const origin = new URL(request.url).origin;
  const specification = createOpenApiDocument(origin);

  return new Response(page(specification), {
    headers: {
      "Content-Type": "text/html; charset=utf-8",
      "Cache-Control": "no-store",
      "X-Content-Type-Options": "nosniff",
      "Referrer-Policy": "no-referrer",
    },
  });
}
