const swaggerJsDoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const jwt = require("jsonwebtoken");
const basicAuth = require("express-basic-auth");

const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || "SailPointIIQLordSolution";

// --- Middleware d'authentification ---
function authenticateToken(req, res, next) {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1]; // Bearer <token>

  if (!token) return res.status(401).json({ message: "Missing token" });

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) return res.status(403).json({ message: "Invalid token" });
    req.user = user;
    next();
  });
}

// --- Configuration Swagger ---
const swaggerOptions = {
  swaggerDefinition: {
    openapi: "3.0.0",
    info: {
      title: "API Partner & Right",
      version: "1.0.0",
      description: "Gestion des partenaires et leurs droits",
      contact: {
        name: "Théophile Tchoffo",
        email: "theo.tchoffo@lordsolution.com",
      },
    },
    servers: [{ url: `http://localhost:${PORT}` }],
  },
  apis: ["./index.js", "./routes/*.js"],
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);

module.exports = (app) => {
  // --- Protection Token pour la doc Swagger ---
  //app.use("/api-docs", authenticateToken, swaggerUi.serve, swaggerUi.setup(swaggerDocs));

  // --- Protection Basic Auth pour la doc Swagger ---
  app.use("/api-docs",
    basicAuth({
      users: { [process.env.BASIC_USER || "spadmin"]: process.env.BASIC_PASS || "admin" },
      challenge: true, // Affiche la fenêtre d’authentification dans le navigateur
      unauthorizedResponse: "Accès refusé : identifiants invalides",
    }),
    swaggerUi.serve,
    swaggerUi.setup(swaggerDocs)
  );
};
