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');

/**
 * Production Confirmation Register Report
 *
 * Query params: companyId, plantId, status, search, dateFrom, dateTo, productionOrderId, page, limit, export
 */
exports.getProductionConfirmationRegisterReport = asyncHandler(async (req, res) => {
  try {
    const {
      page = 1,
      limit = 25,
      export: exportFlag,
      search,
      status,
      companyId,
      plantId,
      dateFrom,
      dateTo,
      productionOrderId,
    } = req.query;

    const isExport = exportFlag === 'true' || exportFlag === true || exportFlag === 1 || exportFlag === '1';
    const effectiveLimit = isExport ? 50000 : parseInt(limit, 10) || 25;
    const effectivePage = isExport ? 1 : parseInt(page, 10) || 1;
    const { limit: limitNum, offset } = getPagination(effectivePage, effectiveLimit);

    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 (productionOrderId) where.production_order_id = productionOrderId;
    if (status && status !== 'ALL') where.status = status;

    if (dateFrom || dateTo) {
      where.confirmation_date = {};
      if (dateFrom) where.confirmation_date[Op.gte] = dateFrom;
      if (dateTo) where.confirmation_date[Op.lte] = dateTo;
    }

    if (search && String(search).trim()) {
      where.confirmation_number = { [Op.like]: `%${String(search).trim()}%` };
    }

    const include = [
      { model: db.Company, as: 'company', attributes: ['id', 'code', 'name'], required: false },
      { model: db.Plant, as: 'plant', attributes: ['id', 'code', 'name'], required: false },
      { model: db.ProductionOrder, as: 'productionOrder', attributes: ['id', 'production_order_number'], required: false },
      { model: db.WorkCenter, as: 'workCenter', attributes: ['id', 'work_center_code', 'description'], required: false },
    ];

    const records = await db.ProductionConfirmation.findAndCountAll({
      where,
      include,
      order: [['confirmation_date', 'DESC'], ['confirmation_number', 'DESC'], ['id', 'DESC']],
      limit: limitNum,
      offset,
    });

    const items = (records.rows || []).map((r) => (r?.toJSON ? r.toJSON() : r));
    const response = getPagingData({ count: records.count || 0, rows: items }, effectivePage, limitNum);

    return sendResponse(res, 200, true, 'Production Confirmation Register generated successfully', response);
  } catch (error) {
    console.error('Production Confirmation Register Report error:', error);
    return sendError(res, error.message || 'Failed to generate Production Confirmation Register', 500);
  }
});
