import type { WeekdayAvailability } from "@capakraken/shared";
import { calculateEffectiveBookedHours } from "../lib/resource-capacity.js";

type BookingForCapacity = {
  startDate: Date;
  endDate: Date;
  hoursPerDay: number;
};

export function toIsoDate(value: Date): string {
  return value.toISOString().slice(0, 10);
}

export function buildDailyBookedHoursMap(
  bookings: BookingForCapacity[],
  availability: WeekdayAvailability,
  context: Parameters<typeof calculateEffectiveBookedHours>[0]["context"],
  periodStart: Date,
  periodEnd: Date,
): Map<string, number> {
  const dailyBookedHours = new Map<string, number>();
  const cursor = new Date(periodStart);
  cursor.setUTCHours(0, 0, 0, 0);
  const end = new Date(periodEnd);
  end.setUTCHours(0, 0, 0, 0);

  while (cursor <= end) {
    const isoDate = toIsoDate(cursor);
    const bookedHours = bookings.reduce(
      (sum, booking) => sum + calculateEffectiveBookedHours({
        availability,
        startDate: booking.startDate,
        endDate: booking.endDate,
        hoursPerDay: booking.hoursPerDay,
        periodStart: cursor,
        periodEnd: cursor,
        context,
      }),
      0,
    );
    dailyBookedHours.set(isoDate, bookedHours);
    cursor.setUTCDate(cursor.getUTCDate() + 1);
  }

  return dailyBookedHours;
}
