import { create } from "zustand";

/**
 * Registering for something that overlaps a registration you already hold
 * (backend `db8dcb2`, `ScheduleConflictService`): `POST
 * /volunteer-opportunity-registrations/` and `POST
 * /learn-serve-opportunity-registrations/` answer **409** with
 * `data.conflict`. The reader chooses: keep the old one (this registration is
 * dropped), or cancel the old one — the same request is sent again with
 * `cancel_conflicting: true`, and the server cancels it under its usual
 * cancellation rules before registering. If that cancel is refused (e.g.
 * within a day of the start), the second request fails with that reason,
 * which the caller shows like any other registration error.
 */
export interface ScheduleConflict {
  type: "volunteer" | "learn_serve" | "event";
  registration_id: number;
  opportunity_id: number;
  title_en: string | null;
  title_ar: string | null;
  /** `YYYY-MM-DD`. */
  date: string | null;
}

interface PendingConflict {
  /** Every registration that overlaps (backend `0572fb7`: `data.conflicts[]`). */
  conflicts: ScheduleConflict[];
  /** The server's localized explanation (`msg`). */
  message: string;
  resolve: (cancelOld: boolean) => void;
}

interface ScheduleConflictState {
  pending: PendingConflict | null;
  /** Opens the dialog; resolves `true` for "cancel the old one and continue". */
  ask: (conflicts: ScheduleConflict[], message: string) => Promise<boolean>;
  answer: (cancelOld: boolean) => void;
}

export const useScheduleConflictStore = create<ScheduleConflictState>((set, get) => ({
  pending: null,
  ask: (conflicts, message) =>
    new Promise<boolean>((resolve) => {
      // A dialog already open is answered "keep" before the new one replaces it.
      get().pending?.resolve(false);
      set({ pending: { conflicts, message, resolve } });
    }),
  answer: (cancelOld) => {
    get().pending?.resolve(cancelOld);
    set({ pending: null });
  },
}));

/**
 * The 409's conflicts, or `null` for any other error. `conflicts[]` lists
 * every overlap (backend `0572fb7`); `conflict` alone is the older shape.
 */
export function scheduleConflictFrom(
  error: unknown
): { conflicts: ScheduleConflict[]; message: string } | null {
  const response = (error as { response?: { status?: number; data?: unknown } })?.response;
  if (response?.status !== 409) return null;
  const body = response.data as
    | { msg?: unknown; data?: { conflict?: ScheduleConflict; conflicts?: ScheduleConflict[] } }
    | undefined;
  const conflicts = body?.data?.conflicts?.length
    ? body.data.conflicts
    : body?.data?.conflict
      ? [body.data.conflict]
      : [];
  if (conflicts.length === 0) return null;
  return { conflicts, message: typeof body?.msg === "string" ? body.msg : "" };
}

/**
 * Runs a registration request and, on a schedule conflict, asks the reader.
 * Returns the response, or `null` when they chose to keep their existing
 * registration (nothing was registered). Any other error — including a
 * refused cancellation on the retry — is thrown to the caller.
 */
export async function registerWithConflictCheck<T>(
  submit: (extra: { cancel_conflicting?: true }) => Promise<T>
): Promise<T | null> {
  try {
    return await submit({});
  } catch (error) {
    const found = scheduleConflictFrom(error);
    if (!found) throw error;
    const cancelOld = await useScheduleConflictStore
      .getState()
      .ask(found.conflicts, found.message);
    if (!cancelOld) return null;
    return submit({ cancel_conflicting: true });
  }
}
