const Permission = require("../models/permissionModel");
const mongoose = require("mongoose");
const {pool} = require("../config/db")

// const upsertDesignationPermission = async (req, res) => {
//   try {
//     const { designationId, permissions, orgId, role } = req.body;

//     if (!role) return res.status(400).json({ message: "role required" });
//     /*  CONVERT STRING → OBJECTID */
//     const orgObjectId = orgId ? new mongoose.Types.ObjectId(orgId) : null;

//     const doc = await Permission.findOneAndUpdate(
//       { role }, //  change from designationId → role
//       {
//         role,
//         orgId :req.user.orgId,
//         permissions,
//         updatedBy: req.user?._id,
//       },
//       {
//         new: true,
//         upsert: true,
//       },
//     );

//     return res.json({
//       success: true,
//       data: doc,
//     });
//   } catch (err) {
//     console.error(err);
//     return res.status(500).json({ message: "Failed to save permissions" });
//   }
// };

// below api is in postgre sql

const upsertDesignationPermission = async (req, res) => {
  const client = await pool.connect();
  try {
    const { designationId, permissions, role } = req.body;

    const orgId = req.session.user.orgId;

    // Validation (same as Mongo)
    if (!role) {
      return res.status(400).json({ message: "role required" });
    }

    // Upsert (based on role)
    const query = `
      INSERT INTO permissions (
        role,
        org_id,
        permissions,
        updated_by,
        updated_at
      )
      VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)
      ON CONFLICT (role)
      DO UPDATE SET
        org_id = EXCLUDED.org_id,
        permissions = EXCLUDED.permissions,
        updated_by = EXCLUDED.updated_by,
        updated_at = CURRENT_TIMESTAMP
      RETURNING *;
    `;

    const values = [
      role,
      req.session.user?.orgId || null,   // same as Mongo
      JSON.stringify(permissions || {}), // store as JSON
      req.session.user?.id || null,
    ];

    const result = await client.query(query, values);

    return res.json({
      success: true,
      data: result.rows[0], // same response structure
    });

  } catch (err) {
    console.error(err);

    return res.status(500).json({
      message: "Failed to save permissions",
    });
  } finally {
    client.release();
  }
};




// const getPermissionByRole = async (req, res) => {
//   try {
//     // const { role } = req.params;
//     const role = req.params.role.toLowerCase();

//     const doc = await Permission.findOne({
//       role,
//       isActive: true,
//     });

//     return res.json({
//       success: true,
//       data: doc || { permissions: [] },
//     });
//   } catch (err) {
//     return res.status(500).json({ message: "Failed" });
//   }
// };

// below api is in postgre sql
const getPermissionByRole = async (req, res) => {
  const client = await pool.connect();

  try {
    // same logic
    const role = req.params.role.toLowerCase();

    const query = `
      SELECT 
        id,
       
        permissions,
        is_active AS "isActive",
        updated_by AS "updatedBy",
        updated_at AS "updatedAt"
      FROM permissions
      WHERE role = $1 AND is_active = TRUE
      LIMIT 1;
    `;

    //   org_id AS "orgId",

    const result = await client.query(query, [role]);

    let data = null;

    if (result.rows.length > 0) {
      data = result.rows[0];

      // parse JSON (same as Mongo object)
      data.permissions =
        typeof data.permissions === "string"
          ? JSON.parse(data.permissions)
          : data.permissions;
    }

    return res.json({
      success: true,
      data: data || { permissions: [] }, //  same fallback
    });

  } catch (err) {
    return res.status(500).json({
      message: "Failed",
    });
  } finally {
    client.release();
  }
};

module.exports = {
  upsertDesignationPermission,
  getPermissionByRole,
};
