import type { GlitchPlayerMode } from "../types/player";
import type { PresentationDefinition } from "../types/lecture";

export const DEFAULT_PRESENTATION_ID = "rethinking-econ-ep1";

export function getPresentationIdFromLocation(search?: string) {
  const resolvedSearch =
    search ?? (typeof window === "undefined" ? "" : window.location.search);
  const params = new URLSearchParams(resolvedSearch);

  return (
    params.get("presentationId") ??
    params.get("lectureId") ??
    DEFAULT_PRESENTATION_ID
  );
}

export function getPlayerModeFromLocation(search?: string): GlitchPlayerMode {
  const resolvedSearch =
    search ?? (typeof window === "undefined" ? "" : window.location.search);
  const params = new URLSearchParams(resolvedSearch);

  return params.get("mode") === "slide-preview" ? "slide-preview" : "playback";
}

export function getTargetSlideIdFromLocation(search?: string) {
  const resolvedSearch =
    search ?? (typeof window === "undefined" ? "" : window.location.search);
  const params = new URLSearchParams(resolvedSearch);

  return params.get("slideId") ?? undefined;
}

export async function fetchPresentationById(
  presentationId: string
): Promise<PresentationDefinition> {
  const response = await fetch(
    `/api/presentations/${encodeURIComponent(presentationId)}`
  );

  if (!response.ok) {
    throw new Error(
      `Presentation fetch failed with ${response.status} for ${presentationId}`
    );
  }

  return (await response.json()) as PresentationDefinition;
}
