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
 */

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 */
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: {
              employee_code: { type: "string" },
              first_name: { type: "string" },
              last_name: { type: "string" },
              email: { type: "string" },
              phone: { type: "string" },
              department_id: { type: "integer" },
              designation_id: { type: "integer" },
              date_of_joining: { type: "string", format: "date" },
              date_of_birth: { type: "string", format: "date" },
              gender: { type: "string", enum: ["male", "female", "other"] },
              marital_status: { type: "string" },
              nationality: { type: "string" },
              pan_number: { type: "string" },
              aadhar_number: { type: "string" },
              passport_number: { type: "string" },
              driving_license: { type: "string" },
              emergency_contact_name: { type: "string" },
              emergency_contact_phone: { type: "string" },
              emergency_contact_relation: { type: "string" },
              current_address: { type: "string" },
              permanent_address: { type: "string" },
              bank_name: { type: "string" },
              account_number: { type: "string" },
              ifsc_code: { type: "string" },
              uan_number: { type: "string" },
              pf_number: { type: "string" },
              esi_number: { type: "string" },
              basic_salary: { type: "number" },
              hra: { type: "number" },
              allowances: { type: "number" },
              deductions: { type: "number" },
              net_salary: { type: "number" },
              reporting_manager_id: { type: "integer" },
              org_id: { type: "string" },
              role_id: { type: "integer" },
              status: { type: "string", enum: ["active", "inactive", "terminated"] },
              // File uploads
              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" }
            },
            required: ["employee_code", "first_name", "email", "department_id", "designation_id", "date_of_joining", "org_id"]
          }
        }
      }
    }
    #swagger.responses[201] = {
      description: 'Employee created successfully'
    }
  */
  controller.createEmployee(req, res);
});

/* READ */
router.get("/all", authenticate, (req, res) => {
  /*
    #swagger.tags = ['Employees']
    #swagger.summary = 'Get all employees with pagination and filters'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['page'] = { in: 'query', type: 'integer', description: 'Page number', default: 1 }
    #swagger.parameters['limit'] = { in: 'query', type: 'integer', description: 'Items per page', default: 10 }
    #swagger.parameters['search'] = { in: 'query', type: 'string', description: 'Search by name, email, or employee code' }
    #swagger.parameters['department_id'] = { in: 'query', type: 'integer', description: 'Filter by department' }
    #swagger.parameters['designation_id'] = { in: 'query', type: 'integer', description: 'Filter by designation' }
    #swagger.parameters['status'] = { in: 'query', type: 'string', enum: ['active', 'inactive', 'terminated'], description: 'Filter by status' }
    #swagger.parameters['org_id'] = { in: 'query', type: 'string', description: 'Filter by organization' }
    #swagger.responses[200] = {
      description: 'Employees retrieved successfully'
    }
  */
  controller.getEmployees(req, res);
});

router.get("/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['Employees']
    #swagger.summary = 'Get employee by ID'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      required: true,
      type: 'string',
      description: 'Employee ID'
    }
    #swagger.responses[200] = {
      description: 'Employee retrieved successfully'
    }
    #swagger.responses[404] = {
      description: 'Employee not found'
    }
  */
  controller.getEmployeeById(req, res);
});

/* UPDATE */
router.put(
  "/:id",
  authenticate,
  upload.fields([
    { 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 },
  ]),
  (req, res) => {
    /*
      #swagger.tags = ['Employees']
      #swagger.summary = 'Update employee by ID with optional file uploads'
      #swagger.security = [{ "bearerAuth": [] }]
      #swagger.consumes = ['multipart/form-data']
      #swagger.parameters['id'] = {
        in: 'path',
        required: true,
        type: 'string',
        description: 'Employee ID'
      }
      #swagger.requestBody = {
        required: true,
        content: {
          "multipart/form-data": {
            schema: {
              type: "object",
              properties: {
                employee_code: { type: "string" },
                first_name: { type: "string" },
                last_name: { type: "string" },
                email: { type: "string" },
                phone: { type: "string" },
                department_id: { type: "integer" },
                designation_id: { type: "integer" },
                date_of_joining: { type: "string", format: "date" },
                date_of_birth: { type: "string", format: "date" },
                gender: { type: "string", enum: ["male", "female", "other"] },
                marital_status: { type: "string" },
                nationality: { type: "string" },
                pan_number: { type: "string" },
                aadhar_number: { type: "string" },
                passport_number: { type: "string" },
                driving_license: { type: "string" },
                emergency_contact_name: { type: "string" },
                emergency_contact_phone: { type: "string" },
                emergency_contact_relation: { type: "string" },
                current_address: { type: "string" },
                permanent_address: { type: "string" },
                bank_name: { type: "string" },
                account_number: { type: "string" },
                ifsc_code: { type: "string" },
                uan_number: { type: "string" },
                pf_number: { type: "string" },
                esi_number: { type: "string" },
                basic_salary: { type: "number" },
                hra: { type: "number" },
                allowances: { type: "number" },
                deductions: { type: "number" },
                net_salary: { type: "number" },
                reporting_manager_id: { type: "integer" },
                role_id: { type: "integer" },
                status: { type: "string", enum: ["active", "inactive", "terminated"] },
                // File uploads
                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" }
              }
            }
          }
        }
      }
      #swagger.responses[200] = {
        description: 'Employee updated successfully'
      }
      #swagger.responses[404] = {
        description: 'Employee not found'
      }
    */
    controller.updateEmployee(req, res);
  }
);

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

/* DOWNLOAD */
router.get("/download/:id", authenticate, async (req, res) => {
  /*
    #swagger.tags = ['Employees']
    #swagger.summary = 'Download employee document or payslip'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      required: true,
      type: 'string',
      description: 'Document or payslip ID'
    }
    #swagger.parameters['type'] = {
      in: 'query',
      type: 'string',
      enum: ['payslip', 'profile', 'document'],
      description: 'Type of document to download'
    }
    #swagger.responses[200] = {
      description: 'File downloaded successfully'
    }
    #swagger.responses[404] = {
      description: 'File not found'
    }
  */
  try {
    const { id } = req.params;

    // Example: fetch payslip data
    const result = await pool.query(
      `SELECT * FROM payslips WHERE id = $1`,
      [id]
    );

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

    const payslip = result.rows[0];

    // ⚡ If PDF already stored
    // res.download(payslip.file_path);

    // ⚡ OR generate dynamically (simple example)
    const filePath = `./uploads/payslips/payslip_${id}.pdf`;

    res.download(filePath);

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

module.exports = router;