require("dotenv").config();
const express = require("express");
const basicAuth = require("express-basic-auth");
const jwt = require("jsonwebtoken");
const db = require("./db");
const swaggerSetup = require("./swagger");

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

const app = express();
app.use(express.json());
swaggerSetup(app);

app.use((req, res, next) => {
  if (req.path === "/favicon.ico") return next(); // Ignorer favicon.ico

  res.on("finish", () => {
    console.log(`${req.method} ${req.originalUrl} HTTP/${req.httpVersion} ${res.statusCode}`);
  });
  next();
});

// --- Authentification basique globale (protège toutes les routes) ---
app.use(basicAuth({
  users: { 
    [process.env.BASIC_USER || "spadmin"]: process.env.BASIC_PASS || "admin"
  },
  challenge: true, // affiche une popup d'auth dans le navigateur
  unauthorizedResponse: (req) => "Access denied : invalid credentials"
}));

// --- 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();
  });
}

// --- Route par token ---
//app.use("/partner", authenticateToken, require("./routes/partner"));

// --- Route par Basic Auth ---
app.use("/partner", require("./routes/partner"));

// Middleware global de gestion des erreurs
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: "An internal error has occurred" });
});

// Middleware global pour désactiver la mise en cache
app.use((req, res, next) => {
  res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");
  res.setHeader("Pragma", "no-cache");
  res.setHeader("Expires", "0");
  res.setHeader("Surrogate-Control", "no-store");
  next();
});

// --- Démarrage du serveur ---
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log(`Documentation Swagger on http://localhost:${PORT}/api-docs`);
});
