/**
 * Current duty helpers: remaining time and active duty lookup.
 * Ported from webapp/js/currentDuty.js (getRemainingTime, findCurrentDuty).
 */

import type { DutyWithUser } from "@/types";

/**
 * Compute remaining time until end of shift. Call only when now < end (active duty).
 *
 * @param endAt - ISO end time of the shift
 * @returns Object with hours and minutes remaining
 */
export function getRemainingTime(endAt: string | Date): { hours: number; minutes: number } {
  const end = new Date(endAt).getTime();
  if (isNaN(end)) return { hours: 0, minutes: 0 };
  const now = Date.now();
  const ms = Math.max(0, end - now);
  const hours = Math.floor(ms / (1000 * 60 * 60));
  const minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60));
  return { hours, minutes };
}

/**
 * Find the duty that is currently active (start <= now < end). Prefer event_type === "duty".
 *
 * @param duties - List of duties with start_at, end_at, event_type
 * @returns The active duty or null
 */
export function findCurrentDuty(duties: DutyWithUser[] | null | undefined): DutyWithUser | null {
  const list = duties ?? [];
  const dutyType = list.filter((d) => d.event_type === "duty");
  const candidates = dutyType.length > 0 ? dutyType : list;
  const now = Date.now();
  for (const d of candidates) {
    const start = new Date(d.start_at).getTime();
    const end = new Date(d.end_at).getTime();
    if (start <= now && now < end) return d;
  }
  return null;
}
