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,
    approvalSteps: booking.approvalSteps,
    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,
    serviceTypeBonus: booking.serviceType?.priorityBonusPoints ?? 0,
    trainScheduleId: booking.trainScheduleId ?? null,
    isGovernment: booking.isGovernment ?? false,
    governmentInstitution: booking.governmentInstitution ?? null,
    consolidationPartnerId: booking.consolidationPartnerId ?? null,
    consolidationPartnerReference: booking.consolidationPartner?.reference ?? null,
    createdAt: booking.createdAt,
  };
}
