import type { BookingDetail, BookingListRow } from "@/types/booking";

function labelFromRef(
  ref?: { name?: string; label?: string; code?: string; companyName?: string },
  fallback = "—",
): string {
  if (!ref) return fallback;
  return (
    ref.companyName ??
    ref.label ??
    ref.name ??
    ref.code ??
    fallback
  );
}

export function toBookingListRow(booking: BookingDetail): BookingListRow {
  return {
    id: booking.id,
    reference: booking.reference,
    contractReference: booking.contractReference ?? null,
    contractId: booking.contractId ?? null,
    customerLabel: booking.isGovernment
      ? (booking.governmentInstitution ?? "Government")
      : labelFromRef(booking.company, booking.companyId ?? undefined),
    // customerLabel: labelFromRef(booking.customer, booking.customerId),
    status: booking.status,
    scheduledDate: booking.scheduledDate,
    totalAmount: Number(booking.totalAmount),
    paymentCurrency: booking.paymentCurrency,
    paymentStatus: booking.paymentStatus,
    tradeDirection: booking.tradeDirection,
    freightType: booking.freightType,
    originLabel: labelFromRef(booking.originYard),
    destinationLabel: labelFromRef(booking.destinationYard),
    priorityScore: booking.priorityScore ?? 0,
    schedulingStatus: booking.schedulingStatus,
    serviceTypeLabel:
      booking.serviceType?.label ??
      booking.serviceType?.name ??
      booking.serviceType?.code,
    trainScheduleId: booking.trainScheduleId ?? null,
    isGovernment: booking.isGovernment ?? false,
    governmentInstitution: booking.governmentInstitution ?? null,
    consolidationPartnerId: booking.consolidationPartnerId ?? null,
    consolidationPartnerReference: booking.consolidationPartner?.reference ?? null,
    customsClearingEnabled: booking.customsClearingEnabled ?? false,
    bookingKind:
      booking.contractKind === "GENERAL" ? "GENERAL_CONTRACT" : "ONE_TIME",
    createdAt: booking.createdAt,
  };
}
