const express = require("express");
const router = express.Router();
const db = require("../db");
const jwt = require("jsonwebtoken");
const swagger = require("../swagger");


// =======================
// SWAGGER CONFIGURATION
// =======================
/**
 * @swagger
 * tags:
 *   name: Partners
 *   description: Gestion des partenaires
 */

/**
 * @swagger
 * components:
 *   schemas:
 *     Partner:
 *       type: object
 *       properties:
 *         partner_id:
 *           type: string
 *         fullname:
 *           type: string
 *         email:
 *           type: string
 *         mobile:
 *           type: string
 *         department:
 *           type: string
 *         jobTitle:
 *           type: string
 *         employeeType:
 *           type: string
 *         status:
 *           type: integer
 *         startDate:
 *           type: string
 *         endDate:
 *           type: string
 */

/**
 * @swagger
 * /partner/:
 *   get:
 *     summary: Vérifie si le endpoint fonctionne
 *     description: Ce endpoint permet de tester si l'API Partner est opérationnelle via Basic Auth.
 *     tags:
 *       - Partners
 *     security:
 *       - basicAuth: []
 *     responses:
 *       200:
 *         description: Ping test réussi, retourne la liste des partenaires avec leurs droits
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/PartnerWithRights'
 *             example:
 *               - id: 1
 *                 name: "Partenaire A"
 *                 rights:
 *                   - "read"
 *                   - "write"
 *               - id: 2
 *                 name: "Partenaire B"
 *                 rights:
 *                   - "read"
 *       401:
 *         description: Non autorisé, Basic Auth manquant ou invalide
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 error:
 *                   type: string
 *                   example: "Authentification requise"
 *       500:
 *         description: Erreur serveur
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 error:
 *                   type: string
 *                   example: "Erreur base de données"
 */
router.get("/", (req, res) => res.send("Ping OK : API Partner is running"));

// =======================
// PARTNERS
// =======================

/**
 * @swagger
 * /partner/all:
 *   get:
 *     summary: Récupère tous les partenaires avec leurs droits concaténés
 *     tags: [Partners]
 *     responses:
 *       200:
 *         description: Liste des partenaires avec droits
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/PartnerWithRights'
 *       500:
 *         description: Erreur serveur
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 error:
 *                   type: string
 *                   example: "Erreur base de données"
 */
router.get("/all", (req, res) => {
  const sql = `
    SELECT 
      p.partner_id,
      p.fullname,
      p.email,
      p.mobile,
      p.department,
      p.jobTitle,
      p.employeeType,
      p.status,
      p.startDate,
      p.endDate,
      COALESCE(GROUP_CONCAT(DISTINCT r.right_id ORDER BY r.right_id SEPARATOR ','), '') AS rights
    FROM partners p
    LEFT JOIN partners_rights pr ON p.partner_id = pr.partner_id
    LEFT JOIN rights r ON pr.right_id = r.right_id
    GROUP BY 
      p.partner_id, p.fullname, p.email, p.mobile, 
      p.department, p.jobTitle, p.employeeType, 
      p.status, p.startDate, p.endDate
    ORDER BY p.partner_id;
  `;

  db.query(sql, (err, results) => {
    if (err) return res.status(500).json({ error: err.message });
    res.json(results);
  });
});

/**
 * @swagger
 * /partner/{partner_id}:
 *   get:
 *     summary: Récupère un partenaire précis avec ses droits concaténés
 *     tags: [Partners]
 *     parameters:
 *       - in: path
 *         name: partner_id
 *         required: true
 *         schema:
 *           type: string
 *         description: ID du partenaire à rechercher
 *     responses:
 *       200:
 *         description: Détails du partenaire avec ses droits concaténés
 */
router.get("/:partner_id", (req, res) => {
  const { partner_id } = req.params;
  const sql = `
    SELECT 
      p.partner_id,
      p.fullname,
      p.email,
      p.mobile,
      p.department,
      p.jobTitle,
      p.employeeType,
      p.status,
      p.startDate,
      p.endDate,
      COALESCE(GROUP_CONCAT(r.right_id ORDER BY r.right_id SEPARATOR ','), '') AS rights
    FROM partners p
    LEFT JOIN partners_rights pr ON p.partner_id = pr.partner_id
    LEFT JOIN rights r ON pr.right_id = r.right_id
    WHERE p.partner_id = ?
    GROUP BY 
      p.partner_id, p.fullname, p.email, p.mobile, 
      p.department, p.jobTitle, p.employeeType, 
      p.status, p.startDate, p.endDate;
  `;
  db.query(sql, [partner_id], (err, results) => {
    if (err) return res.status(500).json({ error: err.message });
    if (results.length === 0) return res.status(404).json({ message: "Partner not found" });
    res.json(results[0]);
  });
});

/**
 * @swagger
 * /partner/provision:
 *   post:
 *     summary: Provisionner un partenaire et ses droits (Create / Modify / Delete)
 *     tags: [Partners]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               operation:
 *                 type: string
 *                 enum: [Create, Modify, Delete]
 *                 description: Type d'opération à effectuer
 *                 example: Create
 *               partner_id:
 *                 type: string
 *                 description: Identifiant du partenaire
 *                 example: P007
 *               fullname:
 *                 type: string
 *               email:
 *                 type: string
 *               mobile:
 *                 type: string
 *               department:
 *                 type: string
 *               jobTitle:
 *                 type: string
 *               employeeType:
 *                 type: string
 *               status:
 *                 type: string
 *               startDate:
 *                 type: string
 *               endDate:
 *                 type: string
 *               rights:
 *                 type: string
 *                 description: Liste des droits à appliquer, séparés par des virgules
 *                 example: "R001,R003"
 *             required:
 *               - partner_id
 *     responses:
 *       200:
 *         description: Partenaire provisionné avec succès
 *       400:
 *         description: Paramètres manquants ou invalides
 *       500:
 *         description: Erreur serveur
 */
router.post("/provision", (req, res) => {
  // --- LOG PRINCIPAL ---
  console.log("=== Incoming request from SailPoint IIQ ===");
  console.log("Request body:", JSON.stringify(req.body, null, 2));
  console.log("===========================================");

  // Lecture des données
  const operation = (req.body.operation || "Create").toLowerCase();
  const {
    partner_id,
    fullname,
    email,
    mobile,
    department,
    jobTitle,
    employeeType,
    status,
    startDate,
    endDate,
    rights
  } = req.body;

  // Vérification de base
  if (!partner_id) {
    console.error("Missing partner_id in request body");
    return res.status(400).json({ error: "partner_id is required" });
  }

  // Transformation des droits en tableau
  const rightsArray = rights
    ? rights.split(",").map(r => r.trim()).filter(r => r !== "")
    : [];

  console.log(`Operation: ${operation.toUpperCase()}`);
  console.log(`Partner ID: ${partner_id}`);
  console.log(`Rights:`, rightsArray.length > 0 ? rightsArray : "(aucun droit)");

  // --- Gestion des opérations ---
  switch (operation) {
    case "create":
      console.log(`Creating or updating partner ${partner_id}...`);
      db.query(
        `INSERT INTO partners 
          (partner_id, fullname, email, mobile, department, jobTitle, employeeType, status, startDate, endDate)
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
          ON DUPLICATE KEY UPDATE
            fullname=VALUES(fullname), email=VALUES(email), mobile=VALUES(mobile),
            department=VALUES(department), jobTitle=VALUES(jobTitle),
            employeeType=VALUES(employeeType), status=VALUES(status),
            startDate=VALUES(startDate), endDate=VALUES(endDate)
        `,
        [partner_id, fullname, email, mobile, department, jobTitle, employeeType, status, startDate, endDate],
        (err) => {
          if (err) {
            console.error("Error inserting partner:", err.message);
            return res.status(500).json({ error: err.message });
          }
          upsertRights(partner_id, rightsArray, res);
        }
      );
      break;

    case "modify":
      console.log(`Modifying partner ${partner_id}...`);
      db.query(
        `UPDATE partners
         SET fullname=?, email=?, mobile=?, department=?, jobTitle=?, employeeType=?, status=?, startDate=?, endDate=?
         WHERE partner_id=?`,
        [fullname, email, mobile, department, jobTitle, employeeType, status, startDate, endDate, partner_id],
        (err) => {
          if (err) {
            console.error("Error updating partner:", err.message);
            return res.status(500).json({ error: err.message });
          }
          upsertRights(partner_id, rightsArray, res);
        }
      );
      break;

    case "delete":
      console.log(`Deleting partner ${partner_id}...`);
      db.query("DELETE FROM partners_rights WHERE partner_id = ?", [partner_id], (err) => {
        if (err) {
          console.error("Error deleting rights:", err.message);
          return res.status(500).json({ error: err.message });
        }
        db.query("DELETE FROM partners WHERE partner_id = ?", [partner_id], (err2, result) => {
          if (err2) {
            console.error("Error deleting partner:", err2.message);
            return res.status(500).json({ error: err2.message });
          }
          if (result.affectedRows === 0) {
            console.warn(`Partner ${partner_id} not found`);
            return res.status(404).json({ message: "Partner not found" });
          }
          console.log(`Partner ${partner_id} and rights deleted successfully`);
          return res.status(200).json({ message: `Partner ${partner_id} and rights deleted successfully` });
        });
      });
      break;

    default:
      console.error(`Invalid operation '${operation}'`);
      return res.status(400).json({ error: `Invalid operation '${operation}'` });
  }

  // --- Fonction interne pour insérer / mettre à jour les droits ---
  function upsertRights(partnerId, rightsArray, res) {
    if (rightsArray.length === 0) {
      console.log(`No rights to assign for partner ${partnerId}`);
      return res.status(200).json({ message: `Partner ${partnerId} provisioned without rights` });
    }

    console.log(`Upserting rights for partner ${partnerId}:`, rightsArray);

    const values = rightsArray.map(r => [partnerId, r]);
    const sql = `
      INSERT INTO partners_rights (partner_id, right_id)
      VALUES ?
      ON DUPLICATE KEY UPDATE right_id=VALUES(right_id)
    `;

    db.query(sql, [values], (err) => {
      if (err) {
        console.error("Error inserting rights:", err.message);
        return res.status(500).json({ error: err.message });
      }
      console.log(`Rights successfully assigned to partner ${partnerId}`);
      return res.status(200).json({ message: `Partner ${partnerId} provisioned with rights ${rightsArray.join(",")}` });
    });
  }
});

/**
 * @swagger
 * /partner/create:
 *   post:
 *     summary: Crée un nouveau partenaire et, optionnellement, lui associe des droits
 *     tags: [Partners]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               partner_id:
 *                 type: string
 *               fullname:
 *                 type: string
 *               email:
 *                 type: string
 *               mobile:
 *                 type: string
 *               department:
 *                 type: string
 *               jobTitle:
 *                 type: string
 *               employeeType:
 *                 type: string
 *               status:
 *                 type: string
 *               startDate:
 *                 type: string
 *               endDate:
 *                 type: string
 *               rights:
 *                 type: string
 *                 description: 'Liste des droits séparés par des virgules, ex: "R001,R002"'
 *             example:
 *               partner_id: "P007"
 *               fullname: "Alice Dupont"
 *               email: "alice.dupont@example.com"
 *               department: "Finance"
 *               jobTitle: "Comptable"
 *               employeeType: "Full-Time"
 *               status: "Active"
 *               startDate: "2025-01-01"
 *               endDate: ""
 *               rights: "R001,R003"
 *     responses:
 *       201:
 *         description: Partenaire créé avec succès
 *       400:
 *         description: Paramètres manquants
 *       500:
 *         description: Erreur serveur
 */
router.post("/create", (req, res) => {
  const {
    partner_id,
    fullname,
    email,
    mobile,
    department,
    jobTitle,
    employeeType,
    status,
    startDate,
    endDate,
    rights
  } = req.body;

  if (!partner_id || !fullname) {
    return res.status(400).json({ error: "partner_id and fullname are required" });
  }

  const rightsArray = rights
    ? rights.split(",").map(r => r.trim()).filter(r => r !== "")
    : [];

  // Vérifier si le partenaire existe
  const checkSql = "SELECT partner_id FROM partners WHERE partner_id = ?";
  db.query(checkSql, [partner_id], (err, existing) => {
    if (err) return res.status(500).json({ error: err.message });

    const insertRightsAndReturn = () => {
      if (rightsArray.length === 0) return returnAllRights();

      const values = rightsArray.map(r => [partner_id, r]);
      const sql = "INSERT IGNORE INTO partners_rights (partner_id, right_id) VALUES ?";
      db.query(sql, [values], (errRights) => {
        if (errRights) return res.status(500).json({ error: errRights.message });
        returnAllRights();
      });
    };

    const returnAllRights = () => {
      db.query("SELECT right_id FROM partners_rights WHERE partner_id = ?", [partner_id], (errRows, rows) => {
        if (errRows) return res.status(500).json({ error: errRows.message });
        res.status(existing.length ? 200 : 201).json({
          message: existing.length ? `Partner ${partner_id} updated successfully` : `Partner ${partner_id} created successfully`,
          partner_id,
          rights: rows.map(r => r.right_id).join(",")
        });
      });
    };

    if (existing.length > 0) {
      // --- UPDATE si le partenaire existe déjà
      const updateFields = [];
      const values = [];
      if (fullname) updateFields.push("fullname = ?"), values.push(fullname);
      if (email) updateFields.push("email = ?"), values.push(email);
      if (mobile) updateFields.push("mobile = ?"), values.push(mobile);
      if (department) updateFields.push("department = ?"), values.push(department);
      if (jobTitle) updateFields.push("jobTitle = ?"), values.push(jobTitle);
      if (employeeType) updateFields.push("employeeType = ?"), values.push(employeeType);
      if (status) updateFields.push("status = ?"), values.push(status);
      if (startDate) updateFields.push("startDate = ?"), values.push(startDate);
      if (endDate) updateFields.push("endDate = ?"), values.push(endDate);

      if (updateFields.length > 0) {
        const updateSql = `UPDATE partners SET ${updateFields.join(", ")} WHERE partner_id = ?`;
        db.query(updateSql, [...values, partner_id], (updateErr) => {
          if (updateErr) return res.status(500).json({ error: updateErr.message });
          insertRightsAndReturn();
        });
      } else {
        insertRightsAndReturn();
      }
    } else {
      // --- CREATE nouveau partenaire
      const sql = `INSERT INTO partners (
        partner_id, fullname, email, mobile, department, jobTitle,
        employeeType, status, startDate, endDate
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;

      db.query(sql, [partner_id, fullname, email, mobile, department, jobTitle, employeeType, status, startDate, endDate],
        (errInsert) => {
          if (errInsert) return res.status(500).json({ error: errInsert.message });
          insertRightsAndReturn();
        }
      );
    }
  });
});

/**
 * @swagger
 * /partner/add:
 *   post:
 *     summary: Ajoute un droit à un partenaire
 *     tags: [Partners]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               partner_id:
 *                 type: string
 *               rights:
 *                 type: string
 *     responses:
 *       201:
 *         description: Droit ajouté au partenaire
 */
router.post("/add", (req, res) => {
  const { partner_id, rights } = req.body;

  if (!partner_id || !rights) {
    return res.status(400).json({ error: "partner_id and rights are required" });
  }

  // Découper et nettoyer la liste des droits
  const rightsArray = rights
    .split(",")
    .map((r) => r.trim())
    .filter((r) => r !== "");

  if (rightsArray.length === 0) {
    return res.status(400).json({ error: "No valid rights provided" });
  }

  // Vérifier si le partenaire existe
  const checkSql = "SELECT partner_id FROM partners WHERE partner_id = ?";
  db.query(checkSql, [partner_id], (errCheck, results) => {
    if (errCheck) return res.status(500).json({ error: errCheck.message });

    // ===================================================
    // Partner inexistant → comportement configurable
    // ===================================================
    if (results.length === 0) {
      // Option 1 : simple message d’erreur
      return res.status(404).json({
        error: `Partner ${partner_id} not found. Cannot assign rights.`,
      });

      // --- Option 2 (alternative) : création automatique du partner ---
      /*
      const createSql = "INSERT INTO partners (partner_id, fullname, status) VALUES (?, ?, ?)";
      db.query(createSql, [partner_id, partner_id, 'A'], (createErr) => {
        if (createErr) return res.status(500).json({ error: createErr.message });
        console.log(`Partner ${partner_id} created automatically`);
        addRights();
      });
      return;
      */
    }

    // ===================================================
    // Partner existe → ajout de droits
    // ===================================================
    const sqlAdd = "INSERT IGNORE INTO partners_rights (partner_id, right_id) VALUES ?";
    const valuesAdd = rightsArray.map((r) => [partner_id, r]);

    db.query(sqlAdd, [valuesAdd], (errInsert, result) => {
      if (errInsert) return res.status(500).json({ error: errInsert.message });

      const addedCount = result.affectedRows || 0;

      res.status(200).json({
        message: `Rights ${rightsArray.join(",")} added to ${partner_id}`,
        addedCount,
      });
    });
  });
});

/**
 * @swagger
 * /partner/update/{partner_id}:
 *   put:
 *     summary: Met à jour un partenaire et ses droits
 *     tags: [Partners]
 *     parameters:
 *       - name: partner_id
 *         in: path
 *         required: true
 *         schema:
 *           type: string
 *         description: ID du partenaire à mettre à jour
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               fullname:
 *                 type: string
 *               email:
 *                 type: string
 *               mobile:
 *                 type: string
 *               department:
 *                 type: string
 *               jobTitle:
 *                 type: string
 *               employeeType:
 *                 type: string
 *               status:
 *                 type: string
 *               startDate:
 *                 type: string
 *               endDate:
 *                 type: string
 *               rights:
 *                 type: string
 *                 description: 'Liste des droits séparés par des virgules, ex: "R001,R002"'
 *             example:
 *               fullname: "Alice Dupont"
 *               email: "alice.dupont@example.com"
 *               mobile: "0601020304"
 *               department: "Finance"
 *               jobTitle: "Comptable"
 *               employeeType: "Full-Time"
 *               status: "Active"
 *               startDate: "2025-01-01"
 *               endDate: ""
 *               rights: "R001,R003"
 *     responses:
 *       200:
 *         description: Partenaire mis à jour avec succès
 *       400:
 *         description: Paramètres manquants
 *       500:
 *         description: Erreur serveur
 */
router.put("/update/:partner_id", (req, res) => {
  const partner_id = req.params.partner_id;
  const {
    fullname,
    email,
    mobile,
    department,
    jobTitle,
    employeeType,
    status,
    startDate,
    endDate,
    rights
  } = req.body;

  const rightsArray = rights
    ? rights.split(",").map(r => r.trim()).filter(r => r !== "")
    : [];

  const updateFields = [];
  const values = [];
  if (fullname) updateFields.push("fullname = ?"), values.push(fullname);
  if (email) updateFields.push("email = ?"), values.push(email);
  if (mobile) updateFields.push("mobile = ?"), values.push(mobile);
  if (department) updateFields.push("department = ?"), values.push(department);
  if (jobTitle) updateFields.push("jobTitle = ?"), values.push(jobTitle);
  if (employeeType) updateFields.push("employeeType = ?"), values.push(employeeType);
  if (status) updateFields.push("status = ?"), values.push(status);
  if (startDate) updateFields.push("startDate = ?"), values.push(startDate);
  if (endDate) updateFields.push("endDate = ?"), values.push(endDate);

  const insertRightsAndReturn = () => {
    if (rightsArray.length === 0) return returnAllRights();
    const valuesRights = rightsArray.map(r => [partner_id, r]);
    const sql = "INSERT IGNORE INTO partners_rights (partner_id, right_id) VALUES ?";
    db.query(sql, [valuesRights], (errRights) => {
      if (errRights) return res.status(500).json({ error: errRights.message });
      returnAllRights();
    });
  };

  const returnAllRights = () => {
    db.query("SELECT right_id FROM partners_rights WHERE partner_id = ?", [partner_id], (errRows, rows) => {
      if (errRows) return res.status(500).json({ error: errRows.message });
      res.status(200).json({
        message: `Partner ${partner_id} updated successfully`,
        partner_id,
        rights: rows.map(r => r.right_id).join(",")
      });
    });
  };

  if (updateFields.length === 0) return insertRightsAndReturn();

  const sql = `UPDATE partners SET ${updateFields.join(", ")} WHERE partner_id = ?`;
  db.query(sql, [...values, partner_id], (err) => {
    if (err) return res.status(500).json({ error: err.message });
    insertRightsAndReturn();
  });
});

/**
 * @swagger
 * /partner/delete/all:
 *   delete:
 *     summary: Supprime tous les droits de tous les partenaires
 *     tags: [Partners]
 *     responses:
 *       200:
 *         description: Droits supprimés avec succès
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *       500:
 *         description: Erreur serveur
 */
router.delete("/delete/all", (req, res) => {
  const sql = "DELETE FROM partners_rights";

  db.query(sql, (err, result) => {
    if (err) return res.status(500).json({ error: err.message });

    res.status(200).json({
      message: `${result.affectedRows} rights removed from all partners`,
    });
  });
});

/**
 * @swagger
 * /partner/right/deleteAll/{partner_id}:
 *   delete:
 *     summary: Supprime tous les droits associés à un partenaire donné
 *     tags: [Partners]
 *     parameters:
 *       - in: path
 *         name: partner_id
 *         required: true
 *         schema:
 *           type: string
 *         description: ID du partenaire dont on veut supprimer les droits
 *     responses:
 *       200:
 *         description: Droits supprimés avec succès
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *       404:
 *         description: Aucun droit trouvé pour ce partenaire
 *       500:
 *         description: Erreur serveur
 */

router.delete("/right/deleteAll/:partner_id", (req, res) => {
  const { partner_id } = req.params;

  if (!partner_id) {
    return res.status(400).json({ error: "partner_id is required" });
  }

  const sql = "DELETE FROM partners_rights WHERE partner_id = ?";

  db.query(sql, [partner_id], (err, result) => {
    if (err) return res.status(500).json({ error: err.message });

    if (result.affectedRows === 0) {
      return res.status(404).json({
        message: `No rights found for the partner ${partner_id}`,
      });
    }

    res.status(200).json({
      message: `${result.affectedRows} rights removed for the partner ${partner_id}`,
    });
  });
});

/**
 * @swagger
 * /partner/remove:
 *   delete:
 *     summary: Supprime une ou plusieurs droits d’un partenaire
 *     tags: [Partners]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               partner_id:
 *                 type: string
 *                 example: "P007"
 *               rights:
 *                 type: string
 *                 description: 'Liste des droits à supprimer, séparés par des virgules, ex: "R001,R003"'
 *                 example: "R001,R003"
 *             required:
 *               - partner_id
 *               - rights
 *     responses:
 *       200:
 *         description: Droit(s) supprimé(s) du partenaire
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "Rights R001,R003 deleted from P007"
 *       400:
 *         description: Paramètres manquants
 *       500:
 *         description: Erreur serveur
 */

router.delete("/remove", (req, res) => {
  const { partner_id, rights } = req.body;

  if (!partner_id || !rights) {
    return res.status(400).json({ error: "partner_id and rights are required" });
  }

  // Découper la chaîne en tableau
  const rightsArray = rights.split(",").map(r => r.trim()).filter(r => r !== "");

  if (rightsArray.length === 0) {
    return res.status(400).json({ error: "No valid rights to delete" });
  }

  // Supprimer les droits dans la table partners_rights
  const sql = `
    DELETE FROM partners_rights
    WHERE partner_id = ? AND right_id IN (?)
  `;

  db.query(sql, [partner_id, rightsArray], (err, result) => {
    if (err) return res.status(500).json({ error: err.message });

    res.status(200).json({
      message: `Rights ${rightsArray.join(",")} deleted from ${partner_id}`
    });
  });
});

/**
 * @swagger
 * /partner/delete/{partner_id}:
 *   delete:
 *     summary: Supprime un partenaire et tous ses droits associés
 *     tags: [Partners]
 *     parameters:
 *       - in: path
 *         name: partner_id
 *         required: true
 *         schema:
 *           type: string
 *         description: Identifiant du partenaire à supprimer
 *     responses:
 *       200:
 *         description: Partenaire supprimé avec succès
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "Partner P007 and 3 rights deleted successfully"
 *       404:
 *         description: Partenaire non trouvé
 *       500:
 *         description: Erreur serveur
 */
router.delete("/delete/:partner_id", (req, res) => {
  const { partner_id } = req.params;

  // Vérifier si le partenaire existe
  db.query("SELECT * FROM partners WHERE partner_id = ?", [partner_id], (err, rows) => {
    if (err) return res.status(500).json({ error: err.message });
    if (rows.length === 0) return res.status(404).json({ error: "Partner not found" });

    // Supprimer les droits associés
    db.query("SELECT COUNT(*) AS count FROM partners_rights WHERE partner_id = ?", [partner_id], (err2, countRows) => {
      if (err2) return res.status(500).json({ error: err2.message });

      const rightsCount = countRows[0].count;

      db.query("DELETE FROM partners_rights WHERE partner_id = ?", [partner_id], (err3) => {
        if (err3) return res.status(500).json({ error: err3.message });

        // Supprimer le partenaire
        db.query("DELETE FROM partners WHERE partner_id = ?", [partner_id], (err4) => {
          if (err4) return res.status(500).json({ error: err4.message });

          res.status(200).json({
            message: `Partner ${partner_id} and ${rightsCount} rights deleted successfully`
          });
        });
      });
    });
  });
});

/**
 * @swagger
 * /partner/enable/{partner_id}:
 *   put:
 *     summary: Active un partenaire (status = 'A')
 *     tags: [Partners]
 *     parameters:
 *       - in: path
 *         name: partner_id
 *         schema:
 *           type: string
 *         required: true
 *     responses:
 *       200:
 *         description: Partenaire activé
 */
router.put("/enable/:partner_id", (req, res) => {
    const { partner_id } = req.params;
    const sql = "UPDATE partners SET status='A' WHERE partner_id=?";
    db.query(sql, [partner_id], (err) => {
        if (err) return res.status(500).json({ error: err.message });
        res.json({ message: "Partner enabled successfully" });
    });
});

/**
 * @swagger
 * /partner/disable/{partner_id}:
 *   put:
 *     summary: Désactive un partenaire (status = 'I')
 *     tags: [Partners]
 *     parameters:
 *       - in: path
 *         name: partner_id
 *         schema:
 *           type: string
 *         required: true
 *     responses:
 *       200:
 *         description: Partenaire désactivé
 */
router.put("/disable/:partner_id", (req, res) => {
    const { partner_id } = req.params;
    const sql = "UPDATE partners SET status='I' WHERE partner_id=?";
    db.query(sql, [partner_id], (err) => {
        if (err) return res.status(500).json({ error: err.message });
        res.json({ message: "Partner disabled successfully" });
    });
});


// --------------------
// SWAGGER DOCUMENTATION
// --------------------

/**
 * @swagger
 * tags:
 *   name: Rights
 *   description: Gestion des droits
 */

// =======================
// RIGHTS
// =======================

/**
 * @swagger
 * components:
 *   schemas:
 *     Right:
 *       type: object
 *       properties:
 *         right_id:
 *           type: string
 *         type_right:
 *           type: string
 *         description:
 *           type: string
 */

/**
 * @swagger
 * /partner/right/all:
 *   get:
 *     summary: Récupérer la liste de tous les droits
 *     tags: [Rights]
 *     responses:
 *       200:
 *         description: Liste des droits
 */
router.get("/right/all", (req, res) => {
  db.query("SELECT * FROM rights", (err, results) => {
    if (err) return res.status(500).json({ error: err });
    res.status(200).json(results);
  });
});

/**
 * @swagger
 * /partner/right/{right_id}:
 *   get:
 *     summary: Récupérer un droit par son ID
 *     tags: [Rights]
 *     parameters:
 *       - in: path
 *         name: right_id
 *         required: true
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: Détails du droit
 */
router.get("/right/:right_id", (req, res) => {
  const { right_id } = req.params;
  db.query(
    "SELECT * FROM rights WHERE right_id = ?",
    [right_id],
    (err, results) => {
      if (err) return res.status(500).json({ error: err });
      if (results.length === 0)
        return res.status(404).json({ message: "Right not found" });
      res.status(200).json(results[0]);
    }
  );
});

/**
 * @swagger
 * /partner/right/create:
 *   post:
 *     summary: Créer un nouveau droit
 *     tags: [Rights]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               right_id:
 *                 type: string
 *               type_right:
 *                 type: string
 *               description:
 *                 type: string
 *     responses:
 *       201:
 *         description: Droit créé
 */
router.post("/right/create", (req, res) => {
  const { right_id, type_right, description } = req.body;
  db.query(
    "INSERT INTO rights (right_id, type_right, description) VALUES (?, ?, ?)",
    [right_id, type_right, description],
    (err) => {
      if (err) return res.status(500).json({ error: err });
      res.status(201).json({ message: "Right created successfully" });
    }
  );
});

/**
 * @swagger
 * /partner/right/update/{right_id}:
 *   put:
 *     summary: Met à jour un droit existant
 *     tags: [Rights]
 *     parameters:
 *       - in: path
 *         name: right_id
 *         required: true
 *         schema:
 *           type: string
 *         description: ID du droit à mettre à jour
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               type_right:
 *                 type: string
 *               description:
 *                 type: string
 *             example:
 *               type_right: "Admin"
 *               description: "Droit d'accès complet"
 *     responses:
 *       200:
 *         description: Droit mis à jour avec succès
 *       400:
 *         description: Paramètres manquants ou invalides
 *       404:
 *         description: Droit non trouvé
 *       500:
 *         description: Erreur serveur
 */
router.put("/right/update/:right_id", (req, res) => {
  const { right_id } = req.params;
  const { type_right, description } = req.body;

  if (!type_right && !description) {
    return res.status(400).json({ error: "At least one field (type_right or description) is required" });
  }

  const updateFields = [];
  const values = [];
  if (type_right) {
    updateFields.push("type_right = ?");
    values.push(type_right);
  }
  if (description) {
    updateFields.push("description = ?");
    values.push(description);
  }

  const sql = `UPDATE rights SET ${updateFields.join(", ")} WHERE right_id = ?`;
  db.query(sql, [...values, right_id], (err, result) => {
    if (err) return res.status(500).json({ error: err.message });
    if (result.affectedRows === 0) return res.status(404).json({ error: "Right not found" });
    res.status(200).json({ message: `Right ${right_id} updated successfully` });
  });
});

/**
 * @swagger
 * /partner/right/delete/{right_id}:
 *   delete:
 *     summary: Supprime un droit
 *     tags: [Rights]
 *     parameters:
 *       - in: path
 *         name: right_id
 *         required: true
 *         schema:
 *           type: string
 *         description: ID du droit à supprimer
 *     responses:
 *       200:
 *         description: Droit supprimé avec succès
 *       404:
 *         description: Droit non trouvé
 *       500:
 *         description: Erreur serveur
 */
router.delete("/right/delete/:right_id", (req, res) => {
  const { right_id } = req.params;

  // Supprimer d'abord les relations avec les partenaires
  db.query("DELETE FROM partners_rights WHERE right_id = ?", [right_id], (err1) => {
    if (err1) return res.status(500).json({ error: err1.message });

    // Supprimer le droit lui-même
    db.query("DELETE FROM rights WHERE right_id = ?", [right_id], (err2, result) => {
      if (err2) return res.status(500).json({ error: err2.message });
      if (result.affectedRows === 0) return res.status(404).json({ error: "Right not found" });

      res.status(200).json({ message: `Right ${right_id} deleted successfully` });
    });
  });
});

module.exports = router;
