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, fromDate, toDate } = 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 (status) {
    where.status = status;
  }

  if (fromDate && toDate) {
    where.attendance_date = {
      [Op.between]: [fromDate, toDate]
    };
  } else if (fromDate) {
    where.attendance_date = {
      [Op.gte]: fromDate
    };
  } else if (toDate) {
    where.attendance_date = {
      [Op.lte]: toDate
    };
  }

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

  const records = await db.Attendance.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.Employee, as: 'employee', attributes: ['id', 'employee_number', 'first_name', 'last_name'] }
    ],
    limit: limitNum,
    offset,
    order: [['attendance_date', 'DESC'], ['id', 'DESC']]
  });

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

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

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

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

  sendResponse(res, 200, true, 'Attendance record retrieved successfully', attendance);
});

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

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

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

  await attendance.update(req.body);
  const updatedAttendance = await db.Attendance.findByPk(id, {
    include: [
      { model: db.Company, as: 'company' },
      { model: db.Plant, as: 'plant' },
      { model: db.Employee, as: 'employee' }
    ]
  });
  sendResponse(res, 200, true, 'Attendance record updated successfully', updatedAttendance);
});

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

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

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

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

