const { formatDateTime } = require("../../src/utils/ecservice-utils");

function buildComandaHeader(order) {
  let header = `=== COMANDA ===\n`;
  if (order.table) header += `TAVOLO: ${order.table.name}\n`;
  if (order.guests) header += `OSPITI: ${order.guests}\n\n`;
  if (order.waiter) header += `CAMERIERE: ${order.waiter.name}\n`;
  if (order.order_date) header += `DATA: ${formatDateTime(order.order_date)}\n\n`;
  return header;
}

function buildComandaBody(order) {
  const items = Array.isArray(order.items) ? order.items : [];
  const specials = Array.isArray(order.specials) ? order.specials : [];
  const notes = Array.isArray(order.notes) ? order.notes : [];
  const combined = [
    ...items.map((item) => ({ ...item, type: "item" })),
    ...specials.map((special) => ({ ...special, type: "special" })),
  ];

  combined.sort((left, right) => (left.sort ?? 0) - (right.sort ?? 0));

  let output = "";
  let currentSort = null;
  let groupItems = [];

  const flushGroup = () => {
    if (groupItems.length === 0) {
      return;
    }

    for (const item of groupItems) {
      if (item.status !== "pending") {
        continue;
      }

      if (item.type === "item") {
        output += `${item.quantity} x ${item.product?.name || item.name || "Unknown Item"}\n`;
        if (item.modifiers?.length) {
          for (const modifier of item.modifiers) {
            output += `    + ${modifier.name}\n`;
          }
        }
        if (item.note) {
          output += `    Note: ${item.note}\n`;
        }
        continue;
      }

      output += `${item.quantity} x ${item.name}\n`;
      if (item.note) {
        output += `     Note: ${item.note}\n`;
      }
    }

    output += `====== SEGUE ======\n`;
    groupItems = [];
  };

  for (const item of combined) {
    if (item.sort !== currentSort) {
      if (currentSort !== null) {
        flushGroup();
      }
      currentSort = item.sort;
      output += `[USCITA > ${item.sort}]${item.type === "special" ? " - Specials" : ""}\n`;
    }
    groupItems.push(item);
  }

  flushGroup();

  if (notes.length > 0) {
    output += `Note:\n`;
    for (const note of notes) {
      output += `- ${note.content}\n`;
    }
  }

  return output;
}

function buildComandaTemplate(order) {
  const header = buildComandaHeader(order);
  const output = buildComandaBody(order);

  return {
    header,
    output,
    printableOutput: `${header}${output}`,
  };
}

module.exports = {
  buildComandaTemplate,
};