/**
 * Normalize POS / legacy print payloads into receipt renderer fields.
 * Accepts alias keys from web POS, mobile, and older integrations.
 */

function pickFirst(obj, keys) {
  for (const key of keys) {
    const val = obj[key];
    if (val == null) continue;
    if (typeof val === "string" && !val.trim()) continue;
    return val;
  }
  return undefined;
}

function normalizeItems(raw) {
  const list = Array.isArray(raw) ? raw : [];
  return list.map((item) => {
    if (!item || typeof item !== "object") {
      return { name: "Item", quantity: 1, price: 0, total: 0 };
    }
    const quantity = Number(item.quantity ?? item.qty ?? 1) || 1;
    const price = Number(item.price ?? item.unitPrice ?? 0) || 0;
    const total =
      Number(item.total ?? item.lineTotal ?? item.amount ?? quantity * price) || 0;
    const name =
      pickFirst(item, [
        "name",
        "menuItemName",
        "itemName",
        "productName",
        "title",
        "description",
      ]) || "Item";
    const options =
      item.options ||
      item.modifiers ||
      item.addons ||
      item.extras ||
      item.variant ||
      item.notes ||
      null;
    const normalized = {
      name: String(name),
      quantity,
      price,
      total,
    };
    if (Array.isArray(options) && options.length) {
      normalized.options = options.map((o) => String(o));
    } else if (typeof options === "string" && options.trim()) {
      normalized.options = [options.trim()];
    }
    return normalized;
  });
}

function normalizePosPayload(raw = {}, businessConfig = {}) {
  const src = raw && typeof raw === "object" ? { ...raw } : {};
  const cfg = businessConfig || {};

  const order = {
    orderNumber:
      pickFirst(src, ["orderNumber", "orderNo", "order_no", "number", "id"]) ||
      "N/A",
    orderType:
      pickFirst(src, ["orderType", "order_type", "type", "serviceType"]) ||
      "dine-in",
    items: normalizeItems(
      src.items ?? src.lineItems ?? src.cart ?? src.orderItems,
    ),
    subtotal: Number(src.subtotal ?? src.subTotal ?? src.itemsTotal ?? 0) || 0,
    total: Number(src.total ?? src.grandTotal ?? src.amountDue ?? 0) || 0,
    discount: Number(src.discount ?? src.discountAmount ?? 0) || 0,
    discountPercent: Number(src.discountPercent ?? src.discount_percent ?? 0) || 0,
    tax: Number(src.tax ?? src.taxAmount ?? src.salesTax ?? src.gst ?? 0) || 0,
    packingCharges: Number(src.packingCharges ?? src.packing ?? src.packingFee ?? 0) || 0,
    deliveryCharges:
      Number(src.deliveryCharges ?? src.delivery ?? src.deliveryFee ?? 0) || 0,
    loyaltyDiscount:
      Number(src.loyaltyDiscount ?? src.loyalty_discount ?? 0) || 0,
    loyaltyPointsApplied:
      Number(src.loyaltyPointsApplied ?? src.loyalty_points ?? 0) || 0,
    paymentMethod: pickFirst(src, ["paymentMethod", "payment_method", "paymentType"]),
    cashReceived: Number(src.cashReceived ?? src.cashGiven ?? src.cash ?? 0) || undefined,
    change: Number(src.change ?? src.changeDue ?? src.change_due ?? 0) || undefined,
    customerName: pickFirst(src, [
      "customerName",
      "customer_name",
      "customerDisplayName",
      "guestName",
    ]),
    customerPhone: pickFirst(src, [
      "customerPhone",
      "customer_phone",
      "customerPhoneNumber",
      "phone",
    ]),
    customerAddress: pickFirst(src, [
      "customerAddress",
      "customer_address",
      "deliveryAddress",
      "address",
    ]),
    notes: pickFirst(src, ["notes", "orderNotes", "specialInstructions", "remarks"]),
    tableNumber: pickFirst(src, ["tableNumber", "tableNo", "table", "table_name"]),
    tableName: pickFirst(src, ["tableName", "tableLabel"]),
    cashierName: pickFirst(src, ["cashierName", "cashier", "staffName", "serverName"]),
    branchName: pickFirst(src, ["branchName", "branch", "branch_name", "locationName"]),
    businessName:
      pickFirst(src, ["businessName", "organizationName", "restaurantName", "storeName"]) ||
      cfg.BUSINESS_NAME,
    businessPhone:
      pickFirst(src, ["businessPhone", "storePhone", "restaurantPhone"]) ||
      cfg.BUSINESS_PHONE,
    businessWebsite:
      pickFirst(src, ["businessWebsite", "website", "storeWebsite"]) ||
      cfg.BUSINESS_WEBSITE,
    businessAddress:
      pickFirst(src, ["businessAddress", "storeAddress", "restaurantAddress"]) ||
      cfg.BUSINESS_ADDRESS,
    businessTagline:
      pickFirst(src, ["businessTagline", "tagline", "slogan"]) || cfg.BUSINESS_TAGLINE,
    ntn: pickFirst(src, ["ntn", "businessNtn", "taxNumber"]),
    strn: pickFirst(src, ["strn", "businessStrn"]),
    taxInfo: pickFirst(src, ["taxInfo", "taxLabel"]),
    fbrIrn: pickFirst(src, ["fbrIrn", "fbr_irn", "irn"]),
    fbrQrPayload: pickFirst(src, ["fbrQrPayload", "fbr_qr", "fbrQr", "fbrPayload"]),
    copyType: src.copyType,
    orderTime: pickFirst(src, ["orderTime", "createdAt", "placedAt", "timestamp"]),
  };

  if (!order.tax && src.taxRate != null && order.subtotal > 0) {
    order.tax = (order.subtotal * Number(src.taxRate)) / 100;
  }

  if (!order.total && order.subtotal) {
    order.total =
      order.subtotal -
      (order.discount || 0) -
      (order.loyaltyDiscount || 0) +
      (order.packingCharges || 0) +
      (order.deliveryCharges || 0) +
      (order.tax || 0);
  }

  if (order.cashReceived != null && !Number.isFinite(order.cashReceived)) {
    delete order.cashReceived;
  }
  if (order.change != null && !Number.isFinite(order.change)) {
    delete order.change;
  }

  return order;
}

module.exports = { normalizePosPayload, normalizeItems, pickFirst };
