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

/**
 * Purchase Requisition Register Report
 *
 * Query params: companyId, plantId, status, search, dateFrom, dateTo, page, limit, export
 */
exports.getPurchaseRequisitionRegisterReport = asyncHandler(async (req, res) => {
  try {
    const {
      page = 1,
      limit = 25,
      export: exportFlag,
      search,
      status,
      companyId,
      plantId,
      dateFrom,
      dateTo,
    } = 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 (status && status !== 'ALL') where.status = status;

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

    if (search && String(search).trim()) {
      where.pr_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.FiscalYear, as: 'fiscalYear', attributes: ['id', 'fiscal_year', 'start_date', 'end_date'], required: false },
      { model: db.Department, as: 'department', attributes: ['id', 'department_code', 'department_name'], required: false },
      { model: db.CostCenter, as: 'costCenter', attributes: ['id', 'cost_center_code', 'description'], required: false },
      { model: db.User, as: 'requestedByUser', attributes: ['id', 'first_name', 'last_name', 'username'], required: false },
      { model: db.User, as: 'submittedByUser', attributes: ['id', 'first_name', 'last_name', 'username'], required: false },
      { model: db.User, as: 'approvedByUser', attributes: ['id', 'first_name', 'last_name', 'username'], required: false },
      { model: db.User, as: 'rejectedByUser', attributes: ['id', 'first_name', 'last_name', 'username'], required: false },
    ];

    const records = await db.PurchaseRequisition.findAndCountAll({
      where,
      include,
      order: [['pr_date', 'DESC'], ['pr_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, 'Purchase Requisition Register generated successfully', response);
  } catch (error) {
    console.error('Purchase Requisition Register Report error:', error);
    return sendError(res, error.message || 'Failed to generate Purchase Requisition Register', 500);
  }
});
