import fs from "node:fs";
import path from "node:path";
import type { IRouter } from "express";
import swaggerUi from "swagger-ui-express";
import YAML from "yaml";

export function setupSwagger(app: IRouter): void {
  const specPath = path.join(process.cwd(), "openapi.yaml");
  const raw = fs.readFileSync(specPath, "utf8");
  const doc = YAML.parse(raw) as object;

  app.get("/openapi.yaml", (_req, res) => {
    res.type("text/yaml; charset=utf-8").send(raw);
  });

  app.get("/openapi.json", (_req, res) => {
    res.json(doc);
  });

  app.use(
    "/docs",
    swaggerUi.serve,
    swaggerUi.setup(doc, {
      customSiteTitle: "DanaSchool API",
      swaggerOptions: {
        persistAuthorization: true,
        withCredentials: true,
        tryItOutEnabled: true,
      },
    }),
  );
}
