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] = [
      { muster_roll_number: { [Op.like]: `%${search}%` } },
      { remarks: { [Op.like]: `%${search}%` } }
    ];
  }

  const records = await db.MusterRoll.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'] }
    ],
    limit: limitNum,
    offset,
    order: [['year', 'DESC'], ['month', 'DESC'], ['id', 'DESC']]
  });

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

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

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

  if (!musterRoll) {
    return sendError(res, 'Muster roll record not found', 404);
  }

  sendResponse(res, 200, true, 'Muster roll record retrieved successfully', musterRoll);
});

exports.create = asyncHandler(async (req, res) => {
  const musterRoll = await db.MusterRoll.create(req.body);
  const musterRollWithRelations = await db.MusterRoll.findByPk(musterRoll.id, {
    include: [
      { model: db.Company, as: 'company' },
      { model: db.Plant, as: 'plant' },
      { model: db.FiscalYear, as: 'fiscalYear' },
      { model: db.Employee, as: 'employee' }
    ]
  });
  sendResponse(res, 201, true, 'Muster roll record created successfully', musterRollWithRelations);
});

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

  if (!musterRoll) {
    return sendError(res, 'Muster roll record not found', 404);
  }

  await musterRoll.update(req.body);
  const updatedMusterRoll = await db.MusterRoll.findByPk(id, {
    include: [
      { model: db.Company, as: 'company' },
      { model: db.Plant, as: 'plant' },
      { model: db.FiscalYear, as: 'fiscalYear' },
      { model: db.Employee, as: 'employee' }
    ]
  });
  sendResponse(res, 200, true, 'Muster roll record updated successfully', updatedMusterRoll);
});

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

  if (!musterRoll) {
    return sendError(res, 'Muster roll record not found', 404);
  }

  if (musterRoll.status === 'LOCKED') {
    return sendError(res, 'Cannot delete locked muster roll record', 400);
  }

  await musterRoll.destroy();
  sendResponse(res, 200, true, 'Muster roll record deleted successfully', null);
});

