// filepath: c:\Users\amaizy\Desktop\cvgen\routes\front.routes.js

const express = require("express");
const router = express.Router();

const {
  getUserProfile,
  scrapeLinkedInProfile,
} = require("../controllers/linkedin");

// Page d'accueil
router.get("/", (req, res) => {
  const user = req.session.user;
  if (user) {
    return res.redirect("/me");
  }

  res.send(`
    <h1>Welcome to the CV Generator Home Page!</h1>
    <a href="/api/auth/linkedin">
      <button>Connexion LinkedIn</button>
    </a>
  `);
});

// Route pour afficher le profil utilisateur (API)
router.get("/profile", getUserProfile);

// Route protégée /me
router.get("/me", async (req, res) => {
  const user = req.session.user;
  if (!user) {
    return res.redirect("/");
  }

  if (!user.linkedinUrl) {
    return res.send(`
      <h2>Bienvenue, ${user.nom} !</h2>
      <form method="POST" action="/api/me/link">
        <label for="linkedinUrl">Votre URL LinkedIn :</label>
        <input type="url" id="linkedinUrl" name="linkedinUrl" placeholder="https://www.linkedin.com/in/votre-profil" required>
        <button type="submit">Enregistrer</button>
      </form>
    `);
  }

  const profile = await scrapeLinkedInProfile(user.linkedinUrl);

  res.send(profile);
});

module.exports = router;
