function money(value) {
  return Number((Number(value || 0)).toFixed(2));
}

function calculateLineItem(item, settings, sellerStateCode, buyerStateCode) {
  const quantity = Number(item.quantity || 0);
  const rate = Number(item.rate || 0);
  const discountPercent = Number(item.discount_percent || 0);
  const gross = quantity * rate;
  const discountAmount = gross * discountPercent / 100;
  const taxableAmount = money(gross - discountAmount);
  const isSameState = String(sellerStateCode || '') === String(buyerStateCode || '');
  const cgstPercent = isSameState ? Number(settings.cgst_percent || 0) : 0;
  const sgstPercent = isSameState ? Number(settings.sgst_percent || 0) : 0;
  const igstPercent = isSameState ? 0 : Number(settings.igst_percent || 0);
  const cgstAmount = money(taxableAmount * cgstPercent / 100);
  const sgstAmount = money(taxableAmount * sgstPercent / 100);
  const igstAmount = money(taxableAmount * igstPercent / 100);
  const totalAmount = money(taxableAmount + cgstAmount + sgstAmount + igstAmount);

  return {
    description: item.description || 'Tissue Paper',
    paper_type: item.paper_type,
    hsn_code: item.hsn_code || settings.default_hsn || '',
    quantity,
    rate,
    discount_percent: discountPercent,
    taxable_amount: taxableAmount,
    cgst_percent: cgstPercent,
    cgst_amount: cgstAmount,
    sgst_percent: sgstPercent,
    sgst_amount: sgstAmount,
    igst_percent: igstPercent,
    igst_amount: igstAmount,
    total_amount: totalAmount
  };
}

function calculateInvoiceTotals(items) {
  const taxable = items.reduce((sum, item) => sum + Number(item.taxable_amount || 0), 0);
  const cgst = items.reduce((sum, item) => sum + Number(item.cgst_amount || 0), 0);
  const sgst = items.reduce((sum, item) => sum + Number(item.sgst_amount || 0), 0);
  const igst = items.reduce((sum, item) => sum + Number(item.igst_amount || 0), 0);
  const rawTotal = taxable + cgst + sgst + igst;
  const roundedTotal = Math.round(rawTotal);
  return {
    taxable_amount: money(taxable),
    cgst_amount: money(cgst),
    sgst_amount: money(sgst),
    igst_amount: money(igst),
    round_off: money(roundedTotal - rawTotal),
    grand_total: money(roundedTotal)
  };
}

module.exports = { money, calculateLineItem, calculateInvoiceTotals };
