const db = require('../models');
const { sendResponse, sendError } = require('../utils/response');
const asyncHandler = require('../middlewares/asyncHandler');

/**
 * Approved Suppliers Report (List API for Reports module)
 *
 * Query params:
 * - companyId (required; defaults to user company)
 * - vendorCategoryId (optional)
 * - search (optional)
 *
 * Note: returns the same report shape used by the legacy master report page:
 * { company, documentNumber, suppliers: [...] }
 */
exports.getApprovedSuppliersReport = asyncHandler(async (req, res) => {
  try {
    const { companyId, company_id, vendorCategoryId, search } = req.query;
    const companyIdValue = companyId || company_id || req.user?.companyId;

    if (!companyIdValue) {
      return sendError(res, 'Company ID is required', 400);
    }

    const where = {
      company_id: companyIdValue,
      bp_type: { [db.Sequelize.Op.in]: ['VENDOR', 'BOTH'] },
      approval_status: 'APPROVED',
      status: 'ACTIVE',
    };

    if (vendorCategoryId && vendorCategoryId !== 'ALL' && vendorCategoryId !== 'null' && vendorCategoryId !== 'undefined') {
      const catId = parseInt(vendorCategoryId, 10);
      if (!isNaN(catId)) where.vendor_category_id = catId;
    }

    const approvedSuppliers = await db.BusinessPartner.findAll({
      where,
      include: [
        {
          model: db.BPAddress,
          as: 'addresses',
          where: {
            status: 'ACTIVE',
            is_default: true,
          },
          required: false,
          include: [
            { model: db.City, as: 'city', attributes: ['id', 'city_name'] },
            { model: db.State, as: 'state', attributes: ['id', 'state_name', 'state_code'] },
            { model: db.Country, as: 'country', attributes: ['id', 'country_name'] },
          ],
        },
        {
          model: db.BPGSTIN,
          as: 'gstins',
          where: {
            status: 'ACTIVE',
            is_default: true,
          },
          required: false,
          include: [{ model: db.State, as: 'state', attributes: ['id', 'state_name', 'gst_state_code'] }],
        },
        {
          model: db.VendorCategory,
          as: 'vendorCategory',
          attributes: ['id', 'category_code', 'category_name'],
          required: false,
        },
      ],
      order: [['name', 'ASC']],
    });

    // Document number
    let documentNumber = null;
    const document = await db.Document.findOne({
      where: {
        company_id: companyIdValue,
        erp_module: 'BUSINESS_PARTNER',
        status: 'ACTIVE',
      },
      order: [['id', 'DESC']],
    });
    if (document) documentNumber = document.document_number;

    // Company details
    const company = await db.Company.findByPk(companyIdValue, {
      attributes: ['id', 'code', 'name', 'legal_name'],
    });
    if (!company) return sendError(res, 'Company not found', 404);

    const suppliers = approvedSuppliers.map((bp) => {
      const defaultAddress = bp.addresses?.[0] || null;
      const defaultGSTIN = bp.gstins?.[0] || null;

      let address = '';
      if (defaultAddress) {
        const parts = [
          defaultAddress.address_line1,
          defaultAddress.address_line2,
          defaultAddress.city?.city_name,
          defaultAddress.state?.state_name,
          defaultAddress.pincode,
        ].filter(Boolean);
        address = parts.join(', ');
      }

      return {
        id: bp.id,
        supplier_code: bp.bp_number || '',
        supplier_name: bp.name,
        contact_no: defaultAddress?.phone || defaultAddress?.mobile || '',
        email: defaultAddress?.email || '',
        website: defaultAddress?.website || '',
        scope_of_supply: bp.vendorCategory?.category_name || '',
        gst_no: defaultGSTIN?.gstin || '',
        pan_no: bp.pan || '',
        address,
      };
    });

    // Optional search filter on formatted fields (kept in JS to cover GST/address too)
    const q = search && String(search).trim() ? String(search).trim().toLowerCase() : '';
    const filtered = q
      ? suppliers.filter((s) => {
          const hay = [
            s.supplier_code,
            s.supplier_name,
            s.contact_no,
            s.email,
            s.website,
            s.scope_of_supply,
            s.gst_no,
            s.pan_no,
            s.address,
          ]
            .filter(Boolean)
            .join(' ')
            .toLowerCase();
          return hay.includes(q);
        })
      : suppliers;

    const reportData = { company, documentNumber, suppliers: filtered };
    return sendResponse(res, 200, true, 'Approved suppliers list retrieved successfully', reportData);
  } catch (error) {
    console.error('Approved Suppliers Report error:', error);
    return sendError(res, error.message || 'Failed to load Approved Suppliers Report', 500);
  }
});

