import { eachNight } from "./dates";

export interface PricingInput {
  basePrice: number;
  weekendPrice?: number | null;
  weekendDays: number[];
  checkIn: Date;
  checkOut: Date;
  nightlyOverride?: number | null;
  discount?: number;
}

export interface PricingResult {
  nights: number;
  nightlyPrice: number; // average nightly (before discount)
  subtotal: number;
  discount: number;
  total: number;
  breakdown: { date: Date; price: number; weekend: boolean }[];
}

/**
 * Base pricing logic: each night uses base price, or weekend price on
 * configured weekend nights. A manual nightly override flattens all nights.
 */
export function computePricing(input: PricingInput): PricingResult {
  const nights = eachNight(input.checkIn, input.checkOut);
  const breakdown = nights.map((date) => {
    const weekend = input.weekendDays.includes(date.getUTCDay());
    const price =
      input.nightlyOverride != null && input.nightlyOverride > 0
        ? input.nightlyOverride
        : weekend && input.weekendPrice
          ? input.weekendPrice
          : input.basePrice;
    return { date, price, weekend };
  });
  const subtotal = breakdown.reduce((s, n) => s + n.price, 0);
  const discount = Math.min(input.discount ?? 0, subtotal);
  return {
    nights: nights.length,
    nightlyPrice: nights.length ? Math.round((subtotal / nights.length) * 100) / 100 : input.basePrice,
    subtotal,
    discount,
    total: Math.max(0, subtotal - discount),
    breakdown,
  };
}

export function paymentStatus(total: number, paid: number): "PAID" | "PARTIAL" | "UNPAID" {
  if (total <= 0) return "PAID";
  if (paid >= total - 0.005) return "PAID";
  if (paid > 0) return "PARTIAL";
  return "UNPAID";
}
