

// // const express = require("express");
// // const router = express.Router();
// // const controller = require("../../controllers/hrandpayrollsController/employeeController");
// // const upload = require("../../middlewares/upload");
// // const authenticate = require("../../middlewares/authenticate");

// // /**
// //  * @swagger
// //  * tags:
// //  *   name: Employees
// //  *   description: Employee management APIs - Create, Read, Update, Delete operations with document uploads
// //  */

// // const uploadFields = [
// //   { name: "profileImage", maxCount: 1 },
// //   { name: "panFile", maxCount: 1 },
// //   { name: "aadharFile", maxCount: 1 },
// //   { name: "passportFile", maxCount: 1 },
// //   { name: "licenseFile", maxCount: 1 },
// //   { name: "offerLetterFile", maxCount: 1 },
// //   { name: "identityProofFile", maxCount: 1 },
// //   { name: "addressProofFile", maxCount: 1 },
// //   { name: "educationCertificatesFile", maxCount: 1 },
// //   { name: "policyAcceptanceFile", maxCount: 1 },
// //   { name: "trainingAssignmentFile", maxCount: 1 },
// // ];

// // /* ===========================
// //    CREATE EMPLOYEE
// // =========================== */
// // router.post("/create", authenticate, upload.fields(uploadFields), (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Create a new employee with document uploads'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   #swagger.consumes = ['multipart/form-data']
// //   #swagger.requestBody = {
// //     required: true,
// //     content: {
// //       'multipart/form-data': {
// //         schema: {
// //           type: "object",
// //           properties: {
// //             // Define your request body properties here
// //           }
// //         }
// //       }
// //     }
// //   }
// //   #swagger.responses[201] = {
// //     description: 'Employee created successfully',
// //     schema: {
// //       type: "object",
// //       properties: {
// //         id: { type: "string" },
// //         name: { type: "string" },
// //         email: { type: "string" }
// //       }
// //     }
// //   }
// //   #swagger.responses[400] = {
// //     description: 'Bad request - Invalid data'
// //   }
// //   #swagger.responses[401] = {
// //     description: 'Unauthorized - Invalid or missing token'
// //   }
// //   */
// //   controller.createEmployee(req, res);
// // });

// // /* ===========================
// //    GET ALL EMPLOYEES (with filters)
// // =========================== */
// // router.get("/all", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Get all employees'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.getEmployees(req, res);
// // });

// // /* ===========================
// //    GET EMPLOYEES BY ORGANIZATION ID
// // =========================== */
// // router.get("/by-organization/:orgId", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Get employees by organization'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.getEmployeesByOrganization(req, res);
// // });

// // /* ===========================
// //    GET EMPLOYEE COUNT BY ORGANIZATION
// // =========================== */
// // router.get("/count/:orgId", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Get employee count by organization'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.getEmployeeCountByOrganization(req, res);
// // });

// // /* ===========================
// //    GET EMPLOYEES BY DEPARTMENT
// // =========================== */
// // router.get("/by-department/:departmentId", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Get employees by department'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.getEmployeesByDepartment(req, res);
// // });

// // /* ===========================
// //    GET EMPLOYEE BY ID
// // =========================== */
// // router.get("/:id", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Get employee by ID'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.getEmployeeById(req, res);
// // });

// // /* ===========================
// //    UPDATE EMPLOYEE
// // =========================== */
// // router.put("/:id", authenticate, upload.fields(uploadFields), (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Update employee'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.updateEmployee(req, res);
// // });

// // /* ===========================
// //    UPDATE EMPLOYEE STATUS
// // =========================== */
// // router.patch("/:id/status", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Update employee status'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.updateEmployeeStatus(req, res);
// // });

// // /* ===========================
// //    DELETE EMPLOYEE (Soft Delete)
// // =========================== */
// // router.delete("/:id", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Delete employee (soft delete)'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.deleteEmployee(req, res);
// // });

// // /* ===========================
// //    COMPLETE ONBOARDING
// // =========================== */
// // router.post("/complete-onboarding", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Complete employee onboarding'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.completeOnboarding(req, res);
// // });

// // /* ===========================
// //    COMPLETE BENEFITS
// // =========================== */
// // router.post("/complete-benefits", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Complete employee benefits'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.completeBenefits(req, res);
// // });

// // /* ===========================
// //    EXIT EMPLOYEE (Terminate/Relieve)
// // =========================== */
// // router.post("/exit", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Exit employee (terminate/relieve)'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.exitEmployee(req, res);
// // });

// // /* ===========================
// //    GET EMPLOYEE STATS
// // =========================== */
// // router.get("/stats/overview", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Get employee stats overview'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.getEmployeeStats(req, res);
// // });

// // /* ===========================
// //    DEBUG - Check organization departments and designations
// // =========================== */
// // router.get("/debug/org/:orgId", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Debug - Check organization departments and designations'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   #swagger.parameters['orgId'] = { in: 'path', required: true, type: 'string' }
// //   */
// //   controller.debugOrgData(req, res);
// // });

// // /* ===========================
// //    DEBUG - Check all employees in database
// // =========================== */
// // router.get("/debug-all", authenticate, (req, res) => {
// //   /*swagger.tags = ['Employees']
// //   #swagger.summary = 'Debug - Check all employees in database'
// //   #swagger.security = [{ "bearerAuth": [] }]
// //   */
// //   controller.debugAllEmployees(req, res);
// // });

// // /* ===========================
// //    DOWNLOAD EMPLOYEE DOCUMENT / PAYSLIP
// // =========================== */
// // router.get("/download/:id", authenticate, async (req, res) => {
// //   try {
// //     const { id } = req.params;
// //     const { type = 'payslip' } = req.query;

// //     // Example: fetch payslip data
// //     const { pool } = require("../../config/db");
// //     const result = await pool.query(
// //       `SELECT * FROM payroll_records WHERE id = $1`,
// //       [id]
// //     );

// //     if (!result.rows.length) {
// //       return res.status(404).json({ message: "Record not found" });
// //     }

// //     const record = result.rows[0];

// //     // For payslip, use the payslip controller
// //     if (type === 'payslip') {
// //       const payslipController = require("../../controllers/hrandpayrollsController/payslipController");
// //       return payslipController.downloadPayslip(req, res);
// //     }

// //     // For regular file downloads
// //     const filePath = record.file_path;
// //     if (!filePath) {
// //       return res.status(404).json({ message: "File not found" });
// //     }
// //     res.download(filePath);

// //   } catch (error) {
// //     console.error("Download error:", error);
// //     res.status(500).json({ message: "Download failed", error: error.message });
// //   }
// // });

// // module.exports = router;

// const express = require("express");
// const router = express.Router();
// const controller = require("../../controllers/hrandpayrollsController/employeeController");
// const upload = require("../../middlewares/upload");
// const authenticate = require("../../middlewares/authenticate");

// /**
//  * @swagger
//  * tags:
//  *   name: Employees
//  *   description: Employee management APIs - Create, Read, Update, Delete operations with document uploads
//  */

// const uploadFields = [
//   { name: "profileImage", maxCount: 1 },
//   { name: "panFile", maxCount: 1 },
//   { name: "aadharFile", maxCount: 1 },
//   { name: "passportFile", maxCount: 1 },
//   { name: "licenseFile", maxCount: 1 },
//   { name: "offerLetterFile", maxCount: 1 },
//   { name: "identityProofFile", maxCount: 1 },
//   { name: "addressProofFile", maxCount: 1 },
//   { name: "educationCertificatesFile", maxCount: 1 },
//   { name: "policyAcceptanceFile", maxCount: 1 },
//   { name: "trainingAssignmentFile", maxCount: 1 },
// ];

// /* ===========================
//    CREATE EMPLOYEE
// =========================== */
// /**
//  * @swagger
//  * /api/employees/create:
//  *   post:
//  *     tags: [Employees]
//  *     summary: Create a new employee with document uploads
//  *     security:
//  *       - bearerAuth: []
//  *     consumes:
//  *       - multipart/form-data
//  *     requestBody:
//  *       required: true
//  *       content:
//  *         multipart/form-data:
//  *           schema:
//  *             type: object
//  *             properties:
//  *               name:
//  *                 type: string
//  *               email:
//  *                 type: string
//  *               phone:
//  *                 type: string
//  *               organizationId:
//  *                 type: string
//  *               departmentId:
//  *                 type: string
//  *               designationId:
//  *                 type: string
//  *               profileImage:
//  *                 type: string
//  *                 format: binary
//  *               panFile:
//  *                 type: string
//  *                 format: binary
//  *               aadharFile:
//  *                 type: string
//  *                 format: binary
//  *               passportFile:
//  *                 type: string
//  *                 format: binary
//  *               licenseFile:
//  *                 type: string
//  *                 format: binary
//  *               offerLetterFile:
//  *                 type: string
//  *                 format: binary
//  *               identityProofFile:
//  *                 type: string
//  *                 format: binary
//  *               addressProofFile:
//  *                 type: string
//  *                 format: binary
//  *               educationCertificatesFile:
//  *                 type: string
//  *                 format: binary
//  *               policyAcceptanceFile:
//  *                 type: string
//  *                 format: binary
//  *               trainingAssignmentFile:
//  *                 type: string
//  *                 format: binary
//  *     responses:
//  *       201:
//  *         description: Employee created successfully
//  *         content:
//  *           application/json:
//  *             schema:
//  *               type: object
//  *               properties:
//  *                 id:
//  *                   type: string
//  *                 name:
//  *                   type: string
//  *                 email:
//  *                   type: string
//  *       400:
//  *         description: Bad request - Invalid data
//  *       401:
//  *         description: Unauthorized - Invalid or missing token
//  */
// router.post("/create", authenticate, upload.fields(uploadFields), (req, res) => {
//   controller.createEmployee(req, res);
// });

// /* ===========================
//    GET ALL EMPLOYEES (with filters)
// =========================== */
// /**
//  * @swagger
//  * /api/employees/all:
//  *   get:
//  *     tags: [Employees]
//  *     summary: Get all employees
//  *     security:
//  *       - bearerAuth: []
//  *     parameters:
//  *       - in: query
//  *         name: page
//  *         schema:
//  *           type: integer
//  *         description: Page number
//  *       - in: query
//  *         name: limit
//  *         schema:
//  *           type: integer
//  *         description: Items per page
//  *       - in: query
//  *         name: search
//  *         schema:
//  *           type: string
//  *         description: Search term
//  *     responses:
//  *       200:
//  *         description: List of employees
//  *       401:
//  *         description: Unauthorized
//  */
// router.get("/all", authenticate, (req, res) => {
//   controller.getEmployees(req, res);
// });

// /* ===========================
//    GET EMPLOYEES BY ORGANIZATION ID
// =========================== */
// /**
//  * @swagger
//  * /api/employees/by-organization/{orgId}:
//  *   get:
//  *     tags: [Employees]
//  *     summary: Get employees by organization
//  *     security:
//  *       - bearerAuth: []
//  *     parameters:
//  *       - in: path
//  *         name: orgId
//  *         required: true
//  *         schema:
//  *           type: string
//  *         description: Organization ID
//  *     responses:
//  *       200:
//  *         description: List of employees in organization
//  *       401:
//  *         description: Unauthorized
//  */
// router.get("/by-organization/:orgId", authenticate, (req, res) => {
//   controller.getEmployeesByOrganization(req, res);
// });

// /* ===========================
//    GET EMPLOYEE COUNT BY ORGANIZATION
// =========================== */
// /**
//  * @swagger
//  * /api/employees/count/{orgId}:
//  *   get:
//  *     tags: [Employees]
//  *     summary: Get employee count by organization
//  *     security:
//  *       - bearerAuth: []
//  *     parameters:
//  *       - in: path
//  *         name: orgId
//  *         required: true
//  *         schema:
//  *           type: string
//  *         description: Organization ID
//  *     responses:
//  *       200:
//  *         description: Employee count
//  *       401:
//  *         description: Unauthorized
//  */
// router.get("/count/:orgId", authenticate, (req, res) => {
//   controller.getEmployeeCountByOrganization(req, res);
// });

// /* ===========================
//    GET EMPLOYEES BY DEPARTMENT
// =========================== */
// /**
//  * @swagger
//  * /api/employees/by-department/{departmentId}:
//  *   get:
//  *     tags: [Employees]
//  *     summary: Get employees by department
//  *     security:
//  *       - bearerAuth: []
//  *     parameters:
//  *       - in: path
//  *         name: departmentId
//  *         required: true
//  *         schema:
//  *           type: string
//  *         description: Department ID
//  *     responses:
//  *       200:
//  *         description: List of employees in department
//  *       401:
//  *         description: Unauthorized
//  */
// router.get("/by-department/:departmentId", authenticate, (req, res) => {
//   controller.getEmployeesByDepartment(req, res);
// });
// router.get("/check-email",authenticate,(req,res)=>{
//  controller.checkEmailExists(req,res);
// } );

// /* ===========================
//    GET EMPLOYEE BY ID
// =========================== */
// /**
//  * @swagger
//  * /api/employees/{id}:
//  *   get:
//  *     tags: [Employees]
//  *     summary: Get employee by ID
//  *     security:
//  *       - bearerAuth: []
//  *     parameters:
//  *       - in: path
//  *         name: id
//  *         required: true
//  *         schema:
//  *           type: string
//  *         description: Employee ID
//  *     responses:
//  *       200:
//  *         description: Employee details
//  *       404:
//  *         description: Employee not found
//  *       401:
//  *         description: Unauthorized
//  */
// router.get("/:id", authenticate, (req, res) => {
//   controller.getEmployeeById(req, res);
// });

// /* ===========================
//    UPDATE EMPLOYEE
// =========================== */
// /**
//  * @swagger
//  * /api/employees/{id}:
//  *   put:
//  *     tags: [Employees]
//  *     summary: Update employee
//  *     security:
//  *       - bearerAuth: []
//  *     consumes:
//  *       - multipart/form-data
//  *     parameters:
//  *       - in: path
//  *         name: id
//  *         required: true
//  *         schema:
//  *           type: string
//  *         description: Employee ID
//  *     requestBody:
//  *       content:
//  *         multipart/form-data:
//  *           schema:
//  *             type: object
//  *             properties:
//  *               name:
//  *                 type: string
//  *               email:
//  *                 type: string
//  *               phone:
//  *                 type: string
//  *               profileImage:
//  *                 type: string
//  *                 format: binary
//  *     responses:
//  *       200:
//  *         description: Employee updated successfully
//  *       404:
//  *         description: Employee not found
//  *       401:
//  *         description: Unauthorized
//  */
// router.put("/:id", authenticate, upload.fields(uploadFields), (req, res) => {
//   controller.updateEmployee(req, res);
// });

// /* ===========================
//    UPDATE EMPLOYEE STATUS
// =========================== */
// /**
//  * @swagger
//  * /api/employees/{id}/status:
//  *   patch:
//  *     tags: [Employees]
//  *     summary: Update employee status
//  *     security:
//  *       - bearerAuth: []
//  *     parameters:
//  *       - in: path
//  *         name: id
//  *         required: true
//  *         schema:
//  *           type: string
//  *         description: Employee ID
//  *     requestBody:
//  *       required: true
//  *       content:
//  *         application/json:
//  *           schema:
//  *             type: object
//  *             properties:
//  *               status:
//  *                 type: string
//  *                 enum: [active, inactive, terminated, on_leave]
//  *     responses:
//  *       200:
//  *         description: Status updated successfully
//  *       401:
//  *         description: Unauthorized
//  */
// router.patch("/:id/status", authenticate, (req, res) => {
//   controller.updateEmployeeStatus(req, res);
// });

// /* ===========================
//    DELETE EMPLOYEE (Soft Delete)
// =========================== */
// /**
//  * @swagger
//  * /api/employees/{id}:
//  *   delete:
//  *     tags: [Employees]
//  *     summary: Delete employee (soft delete)
//  *     security:
//  *       - bearerAuth: []
//  *     parameters:
//  *       - in: path
//  *         name: id
//  *         required: true
//  *         schema:
//  *           type: string
//  *         description: Employee ID
//  *     responses:
//  *       200:
//  *         description: Employee deleted successfully
//  *       404:
//  *         description: Employee not found
//  *       401:
//  *         description: Unauthorized
//  */
// router.delete("/:id", authenticate, (req, res) => {
//   controller.deleteEmployee(req, res);
// });

// /* ===========================
//    COMPLETE ONBOARDING
// =========================== */
// /**
//  * @swagger
//  * /api/employees/complete-onboarding:
//  *   post:
//  *     tags: [Employees]
//  *     summary: Complete employee onboarding
//  *     security:
//  *       - bearerAuth: []
//  *     requestBody:
//  *       required: true
//  *       content:
//  *         application/json:
//  *           schema:
//  *             type: object
//  *             properties:
//  *               employeeId:
//  *                 type: string
//  *               onboardingData:
//  *                 type: object
//  *     responses:
//  *       200:
//  *         description: Onboarding completed successfully
//  *       401:
//  *         description: Unauthorized
//  */
// router.post("/complete-onboarding", authenticate, (req, res) => {
//   controller.completeOnboarding(req, res);
// });

// /* ===========================
//    COMPLETE BENEFITS
// =========================== */
// /**
//  * @swagger
//  * /api/employees/complete-benefits:
//  *   post:
//  *     tags: [Employees]
//  *     summary: Complete employee benefits
//  *     security:
//  *       - bearerAuth: []
//  *     requestBody:
//  *       required: true
//  *       content:
//  *         application/json:
//  *           schema:
//  *             type: object
//  *             properties:
//  *               employeeId:
//  *                 type: string
//  *               benefitsData:
//  *                 type: object
//  *     responses:
//  *       200:
//  *         description: Benefits completed successfully
//  *       401:
//  *         description: Unauthorized
//  */
// router.post("/complete-benefits", authenticate, (req, res) => {
//   controller.completeBenefits(req, res);
// });

// /* ===========================
//    EXIT EMPLOYEE (Terminate/Relieve)
// =========================== */
// /**
//  * @swagger
//  * /api/employees/exit:
//  *   post:
//  *     tags: [Employees]
//  *     summary: Exit employee (terminate/relieve)
//  *     security:
//  *       - bearerAuth: []
//  *     requestBody:
//  *       required: true
//  *       content:
//  *         application/json:
//  *           schema:
//  *             type: object
//  *             properties:
//  *               employeeId:
//  *                 type: string
//  *               exitDate:
//  *                 type: string
//  *                 format: date
//  *               reason:
//  *                 type: string
//  *     responses:
//  *       200:
//  *         description: Employee exited successfully
//  *       401:
//  *         description: Unauthorized
//  */
// router.post("/exit", authenticate, (req, res) => {
//   controller.exitEmployee(req, res);
// });

// /* ===========================
//    GET EMPLOYEE STATS
// =========================== */
// /**
//  * @swagger
//  * /api/employees/stats/overview:
//  *   get:
//  *     tags: [Employees]
//  *     summary: Get employee stats overview
//  *     security:
//  *       - bearerAuth: []
//  *     responses:
//  *       200:
//  *         description: Employee statistics
//  *       401:
//  *         description: Unauthorized
//  */
// router.get("/stats/overview", authenticate, (req, res) => {
//   controller.getEmployeeStats(req, res);
// });

// /* ===========================
//    DEBUG - Check organization departments and designations
// =========================== */
// /**
//  * @swagger
//  * /api/employees/debug/org/{orgId}:
//  *   get:
//  *     tags: [Employees]
//  *     summary: Debug - Check organization departments and designations
//  *     security:
//  *       - bearerAuth: []
//  *     parameters:
//  *       - in: path
//  *         name: orgId
//  *         required: true
//  *         schema:
//  *           type: string
//  *         description: Organization ID
//  *     responses:
//  *       200:
//  *         description: Debug information
//  *       401:
//  *         description: Unauthorized
//  */
// router.get("/debug/org/:orgId", authenticate, (req, res) => {
//   controller.debugOrgData(req, res);
// });

// /* ===========================
//    DEBUG - Check all employees in database
// =========================== */
// /**
//  * @swagger
//  * /api/employees/debug-all:
//  *   get:
//  *     tags: [Employees]
//  *     summary: Debug - Check all employees in database
//  *     security:
//  *       - bearerAuth: []
//  *     responses:
//  *       200:
//  *         description: Debug information
//  *       401:
//  *         description: Unauthorized
//  */
// router.get("/debug-all", authenticate, (req, res) => {
//   controller.debugAllEmployees(req, res);
// });


// /* ===========================
//    DOWNLOAD EMPLOYEE DOCUMENT / PAYSLIP
// =========================== */
// /**
//  * @swagger
//  * /api/employees/download/{id}:
//  *   get:
//  *     tags: [Employees]
//  *     summary: Download employee document or payslip
//  *     security:
//  *       - bearerAuth: []
//  *     parameters:
//  *       - in: path
//  *         name: id
//  *         required: true
//  *         schema:
//  *           type: string
//  *         description: Record ID
//  *       - in: query
//  *         name: type
//  *         schema:
//  *           type: string
//  *           enum: [payslip, document]
//  *         description: Type of file to download
//  *     responses:
//  *       200:
//  *         description: File download
//  *       404:
//  *         description: Record not found
//  *       401:
//  *         description: Unauthorized
//  */
// router.get("/download/:id", authenticate, async (req, res) => {
//   try {
//     const { id } = req.params;
//     const { type = 'payslip' } = req.query;

//     // Example: fetch payslip data
//     const { pool } = require("../../config/db");
//     const result = await pool.query(
//       `SELECT * FROM payroll_records WHERE id = $1`,
//       [id]
//     );

//     if (!result.rows.length) {
//       return res.status(404).json({ message: "Record not found" });
//     }

//     const record = result.rows[0];

//     // For payslip, use the payslip controller
//     if (type === 'payslip') {
//       const payslipController = require("../../controllers/hrandpayrollsController/payslipController");
//       return payslipController.downloadPayslip(req, res);
//     }

//     // For regular file downloads
//     const filePath = record.file_path;
//     if (!filePath) {
//       return res.status(404).json({ message: "File not found" });
//     }
//     res.download(filePath);

//   } catch (error) {
//     console.error("Download error:", error);
//     res.status(500).json({ message: "Download failed", error: error.message });
//   }
// });

// module.exports = router;

const express = require("express");
const router = express.Router();
const controller = require("../../controllers/hrandpayrollsController/employeeController");
const upload = require("../../middlewares/upload");
const authenticate = require("../../middlewares/authenticate");

/**
 * @swagger
 * tags:
 *   name: Employees
 *   description: Employee management APIs - Create, Read, Update, Delete operations with document uploads
 */

const uploadFields = [
  { name: "profileImage", maxCount: 1 },
  { name: "panFile", maxCount: 1 },
  { name: "aadharFile", maxCount: 1 },
  { name: "passportFile", maxCount: 1 },
  { name: "licenseFile", maxCount: 1 },
  { name: "offerLetterFile", maxCount: 1 },
  { name: "identityProofFile", maxCount: 1 },
  { name: "addressProofFile", maxCount: 1 },
  { name: "educationCertificatesFile", maxCount: 1 },
  { name: "policyAcceptanceFile", maxCount: 1 },
  { name: "trainingAssignmentFile", maxCount: 1 },
];

/* ===========================
   CREATE EMPLOYEE
=========================== */
router.post("/create", authenticate, upload.fields(uploadFields), (req, res) => {
  controller.createEmployee(req, res);
});

/* ===========================
   GET ALL EMPLOYEES (with filters)
=========================== */
router.get("/all", authenticate, (req, res) => {
  controller.getEmployees(req, res);
});

/* ===========================
   GET EMPLOYEES BY ORGANIZATION ID
=========================== */
router.get("/by-organization/:orgId", authenticate, (req, res) => {
  controller.getEmployeesByOrganization(req, res);
});

/* ===========================
   GET EMPLOYEE COUNT BY ORGANIZATION
=========================== */
router.get("/count/:orgId", authenticate, (req, res) => {
  controller.getEmployeeCountByOrganization(req, res);
});

/* ===========================
   GET EMPLOYEES BY DEPARTMENT
=========================== */
router.get("/by-department/:departmentId", authenticate, (req, res) => {
  controller.getEmployeesByDepartment(req, res);
});

/* ===========================
   ✅ CHECK EMAIL EXISTS - MUST BE BEFORE /:id ROUTE
=========================== */
router.get("/check-email", authenticate, (req, res) => {
  controller.checkEmailExists(req, res);
});

/* ===========================
   ✅ GRANT ACCESS - MUST BE BEFORE /:id ROUTE
=========================== */
router.post("/grant-access/:id", authenticate, (req, res) => {
  controller.grantAccessOnly(req, res);
});

/* ===========================
   ✅ ACTIVATE EMPLOYEE - MUST BE BEFORE /:id ROUTE
=========================== */
router.post("/activate/:id", authenticate, (req, res) => {
  controller.activateEmployee(req, res);
});

/* ===========================
   ✅ COMPLETE ONBOARDING
=========================== */
router.post("/complete-onboarding", authenticate, (req, res) => {
  controller.completeOnboarding(req, res);
});

/* ===========================
   ✅ COMPLETE BENEFITS
=========================== */
router.post("/complete-benefits", authenticate, (req, res) => {
  controller.completeBenefits(req, res);
});

/* ===========================
   ✅ EXIT EMPLOYEE (Terminate/Relieve)
=========================== */
router.post("/exit", authenticate, (req, res) => {
  controller.exitEmployee(req, res);
});

/* ===========================
   ✅ GET EMPLOYEE STATS
=========================== */
router.get("/stats/overview", authenticate, (req, res) => {
  controller.getEmployeeStats(req, res);
});

/* ===========================
   ✅ DEBUG - Check organization departments and designations
=========================== */
router.get("/debug/org/:orgId", authenticate, (req, res) => {
  controller.debugOrgData(req, res);
});

/* ===========================
   ✅ DEBUG - Check all employees in database
=========================== */
router.get("/debug-all", authenticate, (req, res) => {
  controller.debugAllEmployees(req, res);
});

/* ===========================
   ✅ DOWNLOAD EMPLOYEE DOCUMENT / PAYSLIP
=========================== */
router.get("/download/:id", authenticate, async (req, res) => {
  try {
    const { id } = req.params;
    const { type = 'payslip' } = req.query;

    const { pool } = require("../../config/db");
    const result = await pool.query(
      `SELECT * FROM payroll_records WHERE id = $1`,
      [id]
    );

    if (!result.rows.length) {
      return res.status(404).json({ message: "Record not found" });
    }

    const record = result.rows[0];

    if (type === 'payslip') {
      const payslipController = require("../../controllers/hrandpayrollsController/payslipController");
      return payslipController.downloadPayslip(req, res);
    }

    const filePath = record.file_path;
    if (!filePath) {
      return res.status(404).json({ message: "File not found" });
    }
    res.download(filePath);

  } catch (error) {
    console.error("Download error:", error);
    res.status(500).json({ message: "Download failed", error: error.message });
  }
});

/* ===========================
   ❌ PARAMETER ROUTES - MUST COME LAST
=========================== */

/* ===========================
   GET EMPLOYEE BY ID
=========================== */
router.get("/:id", authenticate, (req, res) => {
  controller.getEmployeeById(req, res);
});

/* ===========================
   UPDATE EMPLOYEE
=========================== */
router.put("/:id", authenticate, upload.fields(uploadFields), (req, res) => {
  controller.updateEmployee(req, res);
});

/* ===========================
   UPDATE EMPLOYEE STATUS
=========================== */
router.patch("/:id/status", authenticate, (req, res) => {
  controller.updateEmployeeStatus(req, res);
});

/* ===========================
   DELETE EMPLOYEE (Soft Delete)
=========================== */
router.delete("/:id", authenticate, (req, res) => {
  controller.deleteEmployee(req, res);
});

module.exports = router;