import type { Prisma, PrismaClient } from "@prisma/client";
import { scheduledSessionDates, type TrainingDateRange } from "./attendanceCalendar.js";
import { dateOnlyLocal, type TraineeRosterRole } from "./traineeRoster.js";

export type TraineeScopeDb = PrismaClient | Prisma.TransactionClient;

function toDbDateNoon(d: Date): Date {
  const x = dateOnlyLocal(d);
  return new Date(`${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, "0")}-${String(x.getDate()).padStart(2, "0")}T12:00:00.000Z`);
}

function effectiveStartDate(startDate: Date, timelineAnchorDate?: Date | null): Date {
  return timelineAnchorDate ?? startDate;
}

/** Scope calendar + holidays for replacement window anchor and attendance eligibility. */
export async function loadAttendanceScopeForTrainee(
  db: TraineeScopeDb,
  args: { projectId: bigint; trainingId: bigint; cohortId: bigint | null; batchId?: bigint | null },
): Promise<{ anchorStart: Date; range: TrainingDateRange; holidayDates: Date[] } | null> {
  const training = await db.training.findFirst({
    where: { id: args.trainingId, projectId: args.projectId },
    select: { startDate: true, endDate: true, timelineAnchorDate: true, sessionWeekdays: true },
  });
  if (!training) return null;
  const holidays = await db.projectHoliday.findMany({
    where: { projectId: args.projectId },
    select: { holidayDate: true },
  });
  const holidayDates = holidays.map((h) => h.holidayDate);
  if (args.batchId) {
    const b = await db.trainingBatch.findFirst({
      where: { id: args.batchId, projectId: args.projectId, trainingId: args.trainingId },
      select: { startDate: true, endDate: true, timelineAnchorDate: true, sessionWeekdays: true, cohortId: true },
    });
    if (!b) return null;
    if (args.cohortId && b.cohortId !== args.cohortId) return null;
    return {
      anchorStart: dateOnlyLocal(effectiveStartDate(b.startDate, b.timelineAnchorDate)),
      range: {
        startDate: effectiveStartDate(b.startDate, b.timelineAnchorDate),
        endDate: b.endDate,
        sessionWeekdays: b.sessionWeekdays ?? training.sessionWeekdays,
      },
      holidayDates,
    };
  }
  if (args.cohortId) {
    const c = await db.trainingCohort.findFirst({
      where: { id: args.cohortId, trainingId: args.trainingId, projectId: args.projectId },
      select: { startDate: true, endDate: true, timelineAnchorDate: true, sessionWeekdays: true },
    });
    if (!c) return null;
    return {
      anchorStart: dateOnlyLocal(effectiveStartDate(c.startDate, c.timelineAnchorDate)),
      range: {
        startDate: effectiveStartDate(c.startDate, c.timelineAnchorDate),
        endDate: c.endDate,
        sessionWeekdays: c.sessionWeekdays ?? training.sessionWeekdays,
      },
      holidayDates,
    };
  }
  return {
    anchorStart: dateOnlyLocal(effectiveStartDate(training.startDate, training.timelineAnchorDate)),
    range: {
      startDate: effectiveStartDate(training.startDate, training.timelineAnchorDate),
      endDate: training.endDate,
      sessionWeekdays: training.sessionWeekdays,
    },
    holidayDates,
  };
}

/** @deprecated Attendance uses delivery batch timeline only; kept for reference. */
export async function computeInitialAttendanceEligibleFrom(
  db: TraineeScopeDb,
  args: {
    projectId: bigint;
    trainingId: bigint;
    cohortId: bigint | null;
    batchId?: bigint | null;
    rosterRole: TraineeRosterRole;
  },
): Promise<Date | null> {
  if (args.rosterRole !== "active") return null;
  const scope = await loadAttendanceScopeForTrainee(db, {
    projectId: args.projectId,
    trainingId: args.trainingId,
    cohortId: args.cohortId,
    batchId: args.batchId,
  });
  if (!scope) return null;
  const dates = scheduledSessionDates(scope.range, scope.holidayDates, scope.range.endDate);
  const first = dates[0];
  return first ? toDbDateNoon(first) : null;
}

/** @deprecated Promotion no longer sets attendanceEligibleFrom. */
export function computePromotionAttendanceEligibleFrom(args: {
  range: TrainingDateRange;
  holidayDates: Date[];
  promotedAt: Date;
}): Date {
  const promo = dateOnlyLocal(args.promotedAt);
  const dates = scheduledSessionDates(args.range, args.holidayDates, args.range.endDate);
  const hit = dates.find((d) => dateOnlyLocal(d).getTime() >= promo.getTime());
  return toDbDateNoon(hit ?? promo);
}
