import type { Moment } from "moment";
import { canEditOrDelete, getOpportunityButtonState, isOpportunityButtonActionable, type OpportunityButtonSource } from "@/features/shared/opportunityButtonState";

/** Keep the click outcome consistent with the state shown on the button. */
export function learnServeRegistrationTarget(source: OpportunityButtonSource | null | undefined, isCreator: boolean, hasToken: boolean, now?: Moment): "edit" | "login" | "unregister" | "register" | null {
  if (!source) return null;
  if (isCreator) return canEditOrDelete(source, now) ? "edit" : null;
  const state = getOpportunityButtonState({ ...source, opportunity_type: "learn_serve_opportunity" }, now);
  if (!isOpportunityButtonActionable(state)) return null;
  if (!hasToken) return "login";
  return state === "unregister" ? "unregister" : "register";
}

/**
 * Whether «تسجيل» opens the slot picker instead of the ordinary confirmation.
 *
 * PDF p.18 registers all four development types the same way; «مساحة» (stored
 * as learning type `Consultation`) has no slot-booking step. The picker is kept
 * only for a legacy «مساحة» record that really carries dated slots — the
 * publish form no longer creates any, so keying on the type alone opened an
 * empty «لا توجد أوقات متاحة» dialog and nobody could register.
 */
export function usesSlotBooking(
  isConsultation: boolean,
  slots: ReadonlyArray<{ date?: string | null }> | null | undefined
): boolean {
  return isConsultation && (slots ?? []).some((slot) => Boolean(slot.date));
}
