/**
 * Movement Dashboard payment gate.
 *
 * A route on day D is available only when the customer's collected
 * payment covers the cumulative Day-wise Itinerary amount from the
 * first day through D. Guaranteed bookings skip the gate entirely.
 *
 * Day amounts mirror the booking detail Day-wise Itinerary card:
 * transport / activity subtotals and special total_price on their
 * date, hotel subtotal prorated per night across [check_in, check_out).
 */
export interface BookingPaymentGateInput {
  is_guaranteed: boolean;
  guarantee_description?: string | null;
  /** Σ collected customer payments, expressed in the itinerary currency. */
  paid: number;
  /** Day-wise itinerary amount keyed by `YYYY-MM-DD`. */
  day_amounts: Map<string, number>;
  /** Itinerary currency code for display (e.g. "AED"). */
  currency_code: string | null;
}

export interface BookingPaymentGate {
  is_guaranteed: boolean;
  guarantee_description?: string | null;
  /** True ⇒ routes on this day stay disabled until more is collected. */
  payment_pending: boolean;
  /** Cumulative day-wise amount from day 1 through the requested date. */
  required_amount: number;
  paid_amount: number;
  currency_code: string | null;
}

const EPSILON = 0.005;

const round2 = (n: number) => Math.round(n * 100) / 100;

export function resolvePaymentGate(
  input: BookingPaymentGateInput | undefined,
  date: string,
): BookingPaymentGate {
  if (!input) {
    return {
      is_guaranteed: false,
      guarantee_description: null,
      payment_pending: false,
      required_amount: 0,
      paid_amount: 0,
      currency_code: null,
    };
  }

  let required = 0;
  for (const [day, amount] of input.day_amounts) {
    if (day <= date) required += amount;
  }

  return {
    is_guaranteed: input.is_guaranteed,
    guarantee_description: input.guarantee_description ?? null,
    payment_pending: !input.is_guaranteed && input.paid + EPSILON < required,
    required_amount: round2(required),
    paid_amount: round2(input.paid),
    currency_code: input.currency_code,
  };
}
