/**
 * Build time-prefix rows for duty items in day detail (single source of time rules).
 * Ported from webapp/js/hints.js getDutyMarkerRows and buildDutyItemTimePrefix.
 */

import { localDateString, formatHHMM } from "./date-utils";
import type { DutyWithUser } from "@/types";

export interface DutyMarkerRow {
  id: number;
  timePrefix: string;
  fullName: string;
  phone?: string | null;
  username?: string | null;
}

function getItemFullName(item: DutyWithUser): string {
  return item.full_name ?? "";
}

/**
 * Build time prefix for one duty item (e.g. "from 09:00 until 18:00").
 */
function buildDutyItemTimePrefix(
  item: DutyWithUser,
  idx: number,
  total: number,
  hintDay: string,
  sep: string,
  fromLabel: string,
  toLabel: string
): string {
  const startAt = item.start_at;
  const endAt = item.end_at;
  const endHHMM = endAt ? formatHHMM(endAt) : "";
  const startHHMM = startAt ? formatHHMM(startAt) : "";
  const startSameDay =
    hintDay && startAt && localDateString(new Date(startAt)) === hintDay;
  const endSameDay =
    hintDay && endAt && localDateString(new Date(endAt)) === hintDay;
  let timePrefix = "";
  if (idx === 0) {
    if (total === 1 && startSameDay && startHHMM) {
      timePrefix = fromLabel + sep + startHHMM;
      if (endSameDay && endHHMM && endHHMM !== startHHMM) {
        timePrefix += " " + toLabel + sep + endHHMM;
      }
    } else if (startSameDay && startHHMM) {
      timePrefix = fromLabel + sep + startHHMM;
      if (endSameDay && endHHMM && endHHMM !== startHHMM) {
        timePrefix += " " + toLabel + sep + endHHMM;
      }
    } else if (endHHMM) {
      timePrefix = toLabel + sep + endHHMM;
    }
  } else if (idx > 0) {
    if (startSameDay && startHHMM) {
      timePrefix = fromLabel + sep + startHHMM;
      if (endHHMM && endSameDay && endHHMM !== startHHMM) {
        timePrefix += " " + toLabel + sep + endHHMM;
      }
    } else if (endHHMM) {
      timePrefix = toLabel + sep + endHHMM;
    }
  }
  return timePrefix;
}

/**
 * Get array of { timePrefix, fullName, phone?, username? } for duty items.
 */
export function getDutyMarkerRows(
  dutyItems: DutyWithUser[],
  hintDay: string,
  timeSep: string,
  fromLabel: string,
  toLabel: string
): DutyMarkerRow[] {
  return dutyItems.map((item, idx) => {
    const timePrefix = buildDutyItemTimePrefix(
      item,
      idx,
      dutyItems.length,
      hintDay,
      timeSep,
      fromLabel,
      toLabel
    );
    return {
      id: item.id,
      timePrefix,
      fullName: getItemFullName(item),
      phone: item.phone,
      username: item.username,
    };
  });
}
