const db = require('../models');
const { sendResponse, sendError } = require('../utils/response');
const asyncHandler = require('../middlewares/asyncHandler');
const { getPagination, getPagingData } = require('../utils/pagination');
const { Op } = require('sequelize');

exports.getAll = asyncHandler(async (req, res) => {
  const { page = 1, limit = 25, search, status, companyId, plantId, employeeId, fiscalYearId, month, year } = req.query;
  const { limit: limitNum, offset } = getPagination(page, limit);

  const where = {};
  
  if (companyId) {
    where.company_id = companyId;
  } else if (req.user && !req.user.isSuperAdmin) {
    where.company_id = req.user.companyId;
  }

  if (plantId) {
    where.plant_id = plantId;
  }

  if (employeeId) {
    where.employee_id = employeeId;
  }

  if (fiscalYearId) {
    where.fiscal_year_id = fiscalYearId;
  }

  if (month) {
    where.month = month;
  }

  if (year) {
    where.year = year;
  }

  if (status) {
    where.status = status;
  }

  if (search) {
    where[Op.or] = [
      { payroll_number: { [Op.like]: `%${search}%` } },
      { remarks: { [Op.like]: `%${search}%` } }
    ];
  }

  const records = await db.Payroll.findAndCountAll({
    where,
    include: [
      { model: db.Company, as: 'company', attributes: ['id', 'code', 'name'] },
      { model: db.Plant, as: 'plant', attributes: ['id', 'code', 'name'], required: false },
      { model: db.FiscalYear, as: 'fiscalYear', attributes: ['id', 'fiscal_year'] },
      { model: db.Employee, as: 'employee', attributes: ['id', 'employee_number', 'first_name', 'last_name'] },
      { model: db.MusterRoll, as: 'musterRoll', required: false }
    ],
    limit: limitNum,
    offset,
    order: [['year', 'DESC'], ['month', 'DESC'], ['id', 'DESC']]
  });

  const response = getPagingData(records, page, limitNum);
  sendResponse(res, 200, true, 'Payroll records retrieved successfully', response);
});

exports.getById = asyncHandler(async (req, res) => {
  const { id } = req.params;

  const payroll = await db.Payroll.findByPk(id, {
    include: [
      { model: db.Company, as: 'company' },
      { model: db.Plant, as: 'plant' },
      { model: db.FiscalYear, as: 'fiscalYear' },
      { model: db.Employee, as: 'employee' },
      { model: db.MusterRoll, as: 'musterRoll' },
      { model: db.PayrollComponent, as: 'components', order: [['display_order', 'ASC']] }
    ]
  });

  if (!payroll) {
    return sendError(res, 'Payroll record not found', 404);
  }

  sendResponse(res, 200, true, 'Payroll record retrieved successfully', payroll);
});

exports.create = asyncHandler(async (req, res) => {
  const transaction = await db.sequelize.transaction();
  
  try {
    const { components, ...payrollData } = req.body;
    const payroll = await db.Payroll.create(payrollData, { transaction });

    if (components && components.length > 0) {
      const payrollComponents = components.map(comp => ({
        ...comp,
        payroll_id: payroll.id
      }));
      await db.PayrollComponent.bulkCreate(payrollComponents, { transaction });
    }

    await transaction.commit();

    const payrollWithRelations = await db.Payroll.findByPk(payroll.id, {
      include: [
        { model: db.Company, as: 'company' },
        { model: db.Plant, as: 'plant' },
        { model: db.FiscalYear, as: 'fiscalYear' },
        { model: db.Employee, as: 'employee' },
        { model: db.MusterRoll, as: 'musterRoll' },
        { model: db.PayrollComponent, as: 'components', order: [['display_order', 'ASC']] }
      ]
    });

    sendResponse(res, 201, true, 'Payroll record created successfully', payrollWithRelations);
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
});

exports.update = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const payroll = await db.Payroll.findByPk(id);

  if (!payroll) {
    return sendError(res, 'Payroll record not found', 404);
  }

  const transaction = await db.sequelize.transaction();

  try {
    const { components, ...payrollData } = req.body;
    await payroll.update(payrollData, { transaction });

    if (components && components.length > 0) {
      await db.PayrollComponent.destroy({ where: { payroll_id: id }, transaction });
      const payrollComponents = components.map(comp => ({
        ...comp,
        payroll_id: id
      }));
      await db.PayrollComponent.bulkCreate(payrollComponents, { transaction });
    }

    await transaction.commit();

    const updatedPayroll = await db.Payroll.findByPk(id, {
      include: [
        { model: db.Company, as: 'company' },
        { model: db.Plant, as: 'plant' },
        { model: db.FiscalYear, as: 'fiscalYear' },
        { model: db.Employee, as: 'employee' },
        { model: db.MusterRoll, as: 'musterRoll' },
        { model: db.PayrollComponent, as: 'components', order: [['display_order', 'ASC']] }
      ]
    });

    sendResponse(res, 200, true, 'Payroll record updated successfully', updatedPayroll);
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
});

exports.delete = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const payroll = await db.Payroll.findByPk(id);

  if (!payroll) {
    return sendError(res, 'Payroll record not found', 404);
  }

  if (payroll.status === 'POSTED') {
    return sendError(res, 'Cannot delete posted payroll record', 400);
  }

  await payroll.destroy();
  sendResponse(res, 200, true, 'Payroll record deleted successfully', null);
});

