import { describe, expect, it } from "vitest";

import type { BookingListRow } from "@/types/booking";
import { groupBookingsByThreeHourWindow } from "./groupBookingsByThreeHourWindow";

function row(
  id: string,
  scheduledDate: string,
  priorityScore: number,
): BookingListRow {
  return {
    id,
    reference: id,
    customerLabel: "Customer",
    status: "PAID",
    scheduledDate,
    totalAmount: 1000,
    paymentCurrency: "ETB",
    paymentStatus: "PAID",
    tradeDirection: "IMPORT",
    freightType: "CONTAINER",
    originLabel: "Djibouti",
    destinationLabel: "Addis",
    priorityScore,
    createdAt: scheduledDate,
  };
}

describe("groupBookingsByThreeHourWindow", () => {
  it("buckets bookings into UTC 3-hour windows", () => {
    const buckets = groupBookingsByThreeHourWindow([
      row("a", "2026-06-20T05:30:00.000Z", 10),
      row("b", "2026-06-20T05:45:00.000Z", 20),
      row("c", "2026-06-20T08:00:00.000Z", 30),
    ]);

    expect(buckets).toHaveLength(2);
    expect(buckets[0]?.bookings.map((b) => b.id)).toEqual(["b", "a"]);
    expect(buckets[1]?.bookings.map((b) => b.id)).toEqual(["c"]);
    expect(buckets[0]?.label).toContain("03:00");
    expect(buckets[1]?.label).toContain("06:00");
  });

  it("places midnight boundary bookings in the correct bucket", () => {
    const buckets = groupBookingsByThreeHourWindow([
      row("late", "2026-06-20T23:45:00.000Z", 5),
      row("early", "2026-06-21T00:15:00.000Z", 15),
    ]);

    expect(buckets).toHaveLength(2);
    expect(buckets[0]?.bookings[0]?.id).toBe("late");
    expect(buckets[1]?.bookings[0]?.id).toBe("early");
  });

  it("sorts within each bucket by priorityScore descending", () => {
    const buckets = groupBookingsByThreeHourWindow([
      row("low", "2026-06-20T06:00:00.000Z", 5),
      row("high", "2026-06-20T06:30:00.000Z", 50),
      row("mid", "2026-06-20T07:00:00.000Z", 25),
    ]);

    expect(buckets[0]?.bookings.map((b) => b.id)).toEqual(["high", "mid", "low"]);
  });
});
