export const MILLISECONDS_PER_DAY = 86_400_000;

export function calculateInclusiveDays(startDate: Date, endDate: Date): number {
  return (endDate.getTime() - startDate.getTime()) / MILLISECONDS_PER_DAY + 1;
}

export function calculateAllocationHours(input: {
  startDate: Date;
  endDate: Date;
  hoursPerDay: number;
}): number {
  return input.hoursPerDay * calculateInclusiveDays(input.startDate, input.endDate);
}

export function getMonthBucketKey(date: Date): string {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
}

export function getWeekBucketKey(date: Date): string {
  const weekStart = new Date(date);
  const day = weekStart.getDay();
  const diff = weekStart.getDate() - day + (day === 0 ? -6 : 1);
  weekStart.setDate(diff);
  return weekStart.toISOString().slice(0, 10);
}

export function getAverageDailyAvailabilityHours(
  availability: Record<string, number | null | undefined> | null | undefined,
): number {
  if (!availability) {
    return 0;
  }

  const totalWeeklyHours = Object.values(availability).reduce(
    (sum: number, hours) => sum + (hours ?? 0),
    0,
  );

  return totalWeeklyHours / 5;
}
