import moment from "moment";

/** Manual corrections can credit at most 24 hours per person and day. */
export const EXTRA_HOURS_AFTER_SESSION = 2;

export interface AttendanceScheduleSource {
  start_time?: string | null;
  end_time?: string | null;
  time_slots?:
    | {
        date?: string | null;
        start_time?: string | null;
        end_time?: string | null;
        hours?: number | null;
      }[]
    | null;
}

export interface SessionOnDate {
  startsAt: moment.Moment;
  endsAt: moment.Moment;
  /** Scheduled length in hours. */
  hours: number;
}

/** `"17:00"` / `"17:00:00"` onto a given day. Null for anything unparseable. */
function atTimeOfDay(day: moment.Moment, time?: string | null) {
  if (!time) return null;
  const [h, m, s] = String(time).split(":").map(Number);
  if (!Number.isFinite(h) || !Number.isFinite(m ?? 0)) return null;
  return day
    .clone()
    .startOf("day")
    .add({ hours: h, minutes: m || 0, seconds: s || 0 });
}

const round2 = (value: number) => Math.round(value * 100) / 100;

/**
 * The session scheduled on `apiDate` (`YYYY-MM-DD`). A per-day slot wins over
 * the opportunity's own times; an end at or before the start rolls to the next
 * day, the same overnight reading `durationInHours()` uses on the backend.
 */
export function sessionOnDate(
  schedule: AttendanceScheduleSource | null | undefined,
  apiDate: string
): SessionOnDate | null {
  if (!schedule || !apiDate) return null;
  const day = moment(apiDate, "YYYY-MM-DD", true);
  if (!day.isValid()) return null;

  const slot = schedule.time_slots?.find((entry) => entry?.date === apiDate);
  const startsAt = atTimeOfDay(day, slot?.start_time ?? schedule.start_time);
  let endsAt = atTimeOfDay(day, slot?.end_time ?? schedule.end_time);
  if (!startsAt || !endsAt) return null;
  if (endsAt.isSameOrBefore(startsAt)) endsAt = endsAt.add(1, "day");

  const hours =
    typeof slot?.hours === "number"
      ? slot.hours
      : round2(endsAt.diff(startsAt, "minutes") / 60);

  return { startsAt, endsAt, hours };
}

/** The server enforces the same daily limit, including manual corrections. */
export function maxCreditableHours(
  _session: SessionOnDate | null,
  _checkedInAt: string | null | undefined
): number { void _session; void _checkedInAt; return 24; }

/** 3.5 → `{ hours: 3, minutes: 30 }`, for showing a decimal as a duration. */
export function splitHours(value: number): { hours: number; minutes: number } {
  const totalMinutes = Math.round(value * 60);
  return { hours: Math.floor(totalMinutes / 60), minutes: totalMinutes % 60 };
}

/** The fields of one attendance row this module reads. */
export interface AttendanceHoursRecord {
  total_hours?: number | null;
  checked_in_at?: string | null;
  /** BE-91 — the server's cap, when sent. */
  max_hours?: number | null;
  /** BE-91 — set once the organizer corrected this row by hand. */
  hours_set_manually_at?: string | null;
}

/**
 * What the hours cell needs to know about one row, in one place.
 *
 * The server's `max_hours` wins where it is sent; the schedule derives it
 * otherwise. Like the server, the derived cap never drops below what is
 * already credited — a full-session credit from a late scan must stay
 * re-savable.
 *
 * **`hours_set_manually_at` counts as logged** even at zero hours: the
 * organizer deliberately credited nothing, and that is a decision, not a gap.
 */
export function attendanceHoursState(
  record: AttendanceHoursRecord,
  _session: SessionOnDate | null
): {
  maxHours: number | null;
  hasLoggedHours: boolean;
} {
  void _session;
  return {
    maxHours: 24,
    hasLoggedHours: Boolean(record.hours_set_manually_at) || (record.total_hours ?? 0) > 0,
  };
}
