import { sessionDateKey, type TrainingDateRange } from "./attendanceCalendar.js";
import { dateOnlyLocal } from "./traineeRoster.js";

/**
 * All scheduled sessions in the delivery batch range count (no per-trainee promotion cutoff).
 * `attendanceEligibleFrom` is retained on the row for audit but not applied in calculations.
 */
export function filterScheduledDatesFromEligibleStart(
  sessionDatesOrdered: Date[],
  _attendanceEligibleFrom?: Date | null | undefined,
): Date[] {
  return sessionDatesOrdered;
}

export function eligibleSessionKeysForTrainee(args: {
  sessionDatesOrdered: Date[];
  attendanceEligibleFrom: Date | null | undefined;
  excludedSessionKeys: Set<string>;
}): string[] {
  const subset = filterScheduledDatesFromEligibleStart(args.sessionDatesOrdered, args.attendanceEligibleFrom);
  return subset.map((d) => sessionDateKey(d)).filter((k) => !args.excludedSessionKeys.has(k));
}

export type AttendanceBreakdownRow = {
  cohortId: bigint | null;
  batchId?: bigint | null;
  breakStartDate: Date;
  breakEndDate: Date;
};

export function traineeBreakdownExcludedKeys(
  breakdowns: Array<{ cohortId: bigint | null; breakStartDate: Date; breakEndDate: Date }>,
  traineeCohortId: bigint | null,
): Set<string> {
  const excluded = new Set<string>();
  for (const b of breakdowns) {
    if (b.cohortId && b.cohortId !== traineeCohortId) continue;
    const s = new Date(`${b.breakStartDate.toISOString().slice(0, 10)}T00:00:00.000Z`);
    const e = new Date(`${b.breakEndDate.toISOString().slice(0, 10)}T00:00:00.000Z`);
    for (let d = new Date(s); d <= e; d.setUTCDate(d.getUTCDate() + 1)) {
      excluded.add(sessionDateKey(d));
    }
  }
  return excluded;
}

/** Approved breakdown applies: training-wide, cohort-wide for this trainee, or batch-specific. */
export function traineeBreakdownExcludedKeysForDeliveryBatch(
  breakdowns: AttendanceBreakdownRow[],
  traineeCohortId: bigint | null,
  deliveryBatchId: bigint,
): Set<string> {
  const excluded = new Set<string>();
  for (const b of breakdowns) {
    const appliesToBatch =
      b.batchId != null
        ? b.batchId === deliveryBatchId
        : b.cohortId != null
          ? b.cohortId === traineeCohortId
          : true;
    if (!appliesToBatch) continue;
    const s = new Date(`${b.breakStartDate.toISOString().slice(0, 10)}T00:00:00.000Z`);
    const e = new Date(`${b.breakEndDate.toISOString().slice(0, 10)}T00:00:00.000Z`);
    for (let d = new Date(s); d <= e; d.setUTCDate(d.getUTCDate() + 1)) {
      excluded.add(sessionDateKey(d));
    }
  }
  return excluded;
}

export function trainingRangeForTraineeScope(args: {
  training: TrainingDateRange;
  cohort: { startDate: Date; endDate: Date; sessionWeekdays: unknown } | null;
}): TrainingDateRange {
  if (args.cohort) {
    return {
      startDate: args.cohort.startDate,
      endDate: args.cohort.endDate,
      sessionWeekdays: args.cohort.sessionWeekdays ?? args.training.sessionWeekdays,
    };
  }
  return args.training;
}
