import { apiPost } from "@/lib/api/client";
import type { Order } from "@/lib/api/types";
import { iranMobileForApi } from "@/lib/phone";

export type SubmitOrderCart = {
  getPendingLines: () => { menuItemId: string; quantity: number; notes?: string }[];
  activeOrderId: string | null;
  tableId: string | null;
  guestName: string;
  guestPhone: string;
  customerId: string | null;
  appliedCoupon: { id: string } | null;
};

export type SubmitOrderParams = {
  cafeId: string;
  orderBranchId: string | undefined;
  cart: SubmitOrderCart;
  reservationId: string | null;
};

export async function submitOrderToApi({
  cafeId,
  orderBranchId,
  cart,
  reservationId,
}: SubmitOrderParams): Promise<Order> {
  const pending = cart.getPendingLines();
  if (pending.length === 0) throw new Error("nothing pending");

  if (cart.activeOrderId) {
    return apiPost<Order>(`/api/cafes/${cafeId}/orders/${cart.activeOrderId}/items`, {
      items: pending,
    });
  }

  return apiPost<Order>(`/api/cafes/${cafeId}/orders`, {
    orderType: "DineIn",
    branchId: orderBranchId,
    tableId: cart.tableId ?? undefined,
    reservationId: reservationId ?? undefined,
    guestName: cart.guestName.trim() || undefined,
    guestPhone: iranMobileForApi(cart.guestPhone),
    customerId: cart.customerId ?? undefined,
    couponId: cart.appliedCoupon?.id,
    items: pending,
  });
}

export function orderAmountDue(order: Order): number {
  return Math.max(0, order.total - (order.paidAmount ?? 0));
}
