import express from "express";
import pkg from "pg";
import cors from "cors";
import dotenv from "dotenv";

dotenv.config();
const { Pool } = pkg;
const app = express();

// --- CORS sécurisé ---
app.use(
  cors({
    origin: [
      "http://localhost:5173",            // pour tests locaux
      "https://dsp5-archi-o24a-15m-g3.fr" // ton frontend en production
    ],
    credentials: true,
  })
);

app.use(express.json());

// --- Connexion PostgreSQL ---
const pool = new Pool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
  port: 5432,
});

// --- Vérification de la base ---
app.get("/db-check", async (req, res) => {
  try {
    const result = await pool.query("SELECT NOW()");
    res.json({
      message: "✅ Connexion PostgreSQL OK",
      time: result.rows[0].now,
    });
  } catch (err) {
    console.error("Erreur DB:", err.message);
    res.status(500).json({ error: "❌ Connexion à la base échouée" });
  }
});

// --- Route de test ---
app.get("/", (req, res) => {
  res.json({ message: "The Tip Top API is running 🚀" });
});

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