import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import helmet from "helmet";
import morgan from "morgan";
import client from "prom-client";
import { pool } from "./db.js";


dotenv.config();
const app = express();

// --- Middlewares globaux ---
app.use(
  cors({
    origin: ["http://localhost:5173", "https://dsp5-archi-o24a-15m-g3.fr"],
    credentials: true,
  })
);
app.use(helmet());
app.use(morgan("tiny"));
app.use(express.json());

// --- Vérification connexion DB ---
app.get("/db-check", async (req, res) => {
  try {
    const result = await pool.query("SELECT NOW()");
    res.json({ message: "✅ DB connectée", time: result.rows[0].now });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});


// --- Route d’accueil (fix pour 'Cannot GET /') ---
app.get("/", (req, res) => {
  res.json({ message: "✅ API Thé Tip Top en ligne et opérationnelle !" });
});

// --- Monitoring Prometheus ---
const collectDefaultMetrics = client.collectDefaultMetrics;
collectDefaultMetrics();
app.get("/metrics", async (req, res) => {
  res.set("Content-Type", client.register.contentType);
  res.end(await client.register.metrics());
});

// --- Lancement du serveur ---
const PORT = process.env.PORT || 4000;
app.listen(PORT, "0.0.0.0", () => console.log(`🚀 Backend lancé sur ${PORT}`));

