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

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

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

    if (search && String(search).trim()) {
      const q = String(search).trim();
      where[Op.or] = [
        { invoice_number: { [Op.like]: `%${q}%` } },
        { vendor_invoice_number: { [Op.like]: `%${q}%` } },
      ];
    }

    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.BusinessPartner, as: 'vendor', attributes: ['id', 'bp_number', 'name', 'legal_name'], required: false },
      { model: db.GoodsReceiptNote, as: 'goodsReceiptNote', attributes: ['id', 'grn_number'], required: false },
      { model: db.PurchaseOrder, as: 'purchaseOrder', attributes: ['id', 'po_number'], required: false },
    ];

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