(function attachConfirmation(global: any) {
  type ConfirmationItem = {
    item_name: string;
    quantity: number;
    portion_breakup?: Array<{ portion: "full" | "half"; qty: number }>;
    packing_note?: string;
    line_total: number;
  };

  type ConfirmationOrder = {
    address: string;
    items: ConfirmationItem[];
    order_total: number;
  };

  function rupees(value: number): string {
    const amount = Number(value || 0);
    return Number.isInteger(amount) ? `₹${amount}` : `₹${amount.toFixed(2)}`;
  }

  function generateConfirmationMessage(order: ConfirmationOrder): string {
    const itemLines = order.items
      .map((item, index) => {
        const shouldShowBreakup = Boolean(item.portion_breakup?.some((part) => part.portion === "half") || (item.portion_breakup?.length || 0) > 1);
        const portionText = shouldShowBreakup
          ? item.portion_breakup.map((part) => `${part.qty} ${part.portion}`).join(" + ")
          : `x ${item.quantity}`;
        const packing = item.packing_note ? ` | ${item.packing_note}` : "";
        return `${index + 1}. ${item.item_name} ${portionText}${packing} = ${rupees(item.line_total)}`;
      })
      .join("\n");

    return `नमस्कार 🙏
आपली Rama Foods ची ऑर्डर कन्फर्म झाली आहे.

ऑर्डर तपशील:
${itemLines || "-"}

एकूण रक्कम: ${rupees(order.order_total)}

पत्ता:
${order.address || "Address missing"}

कृपया तपशील योग्य असल्यास OK पाठवा.

धन्यवाद,
Rama Foods`;
  }

  const api = { generateConfirmationMessage };
  global.RamaConfirmation = api;
  if (typeof module !== "undefined" && module.exports) {
    module.exports = api;
  }
})(typeof globalThis !== "undefined" ? globalThis : window);
