import type { AdminOrderDetail, AdminOrderListItem, PublicOrder, PublicOrderItem } from "../@types/orders.js";

type BaseOrderRow = {
  id: number;
  orderNumber: string;
  status: PublicOrder["status"];
  fulfillmentMethod: PublicOrder["fulfillmentMethod"];
  contactPhone: string;
  deliveryAddress: string | null;
  subtotal: number;
  totalDiscount: number;
  totalAmount: number;
  paymentMethod: PublicOrder["paymentMethod"];
  paymentStatus: PublicOrder["paymentStatus"];
  customerNotes: string | null;
  staffNotes?: string | null;
  createdAt: Date;
  updatedAt: Date;
};

export const toPublicOrderItem = (item: PublicOrderItem): PublicOrderItem => ({
  id: item.id,
  productId: item.productId,
  productName: item.productName,
  sku: item.sku,
  quantity: item.quantity,
  unitPrice: item.unitPrice,
  discountAmount: item.discountAmount,
  lineTotal: item.lineTotal,
  lensChoice: item.lensChoice,
  prescriptionUrl: item.prescriptionUrl,
});

export const toPublicOrder = (order: BaseOrderRow, items: PublicOrderItem[]): PublicOrder => ({
  id: order.id,
  orderNumber: order.orderNumber,
  status: order.status,
  fulfillmentMethod: order.fulfillmentMethod,
  contactPhone: order.contactPhone,
  deliveryAddress: order.deliveryAddress,
  subtotal: order.subtotal,
  totalDiscount: order.totalDiscount,
  totalAmount: order.totalAmount,
  paymentMethod: order.paymentMethod,
  paymentStatus: order.paymentStatus,
  customerNotes: order.customerNotes,
  createdAt: order.createdAt,
  updatedAt: order.updatedAt,
  items,
});

export const toAdminOrderListItem = (
  order: BaseOrderRow,
  customer: AdminOrderListItem["customer"],
  managedByStaff: AdminOrderListItem["managedByStaff"],
  itemCount: number,
): AdminOrderListItem => ({
  id: order.id,
  orderNumber: order.orderNumber,
  status: order.status,
  fulfillmentMethod: order.fulfillmentMethod,
  contactPhone: order.contactPhone,
  deliveryAddress: order.deliveryAddress,
  subtotal: order.subtotal,
  totalDiscount: order.totalDiscount,
  totalAmount: order.totalAmount,
  paymentMethod: order.paymentMethod,
  paymentStatus: order.paymentStatus,
  customerNotes: order.customerNotes,
  createdAt: order.createdAt,
  updatedAt: order.updatedAt,
  customer,
  managedByStaff,
  itemCount,
});

export const toAdminOrderDetail = (
  listItem: AdminOrderListItem,
  items: PublicOrderItem[],
  staffNotes: string | null,
): AdminOrderDetail => ({
  ...listItem,
  items,
  staffNotes,
});
