import { BAKED_FUNNELS } from "./bakedFunnels";
import type { FunnelDefinition } from "./types";

function resolveBakedFunnel(funnelId: string): FunnelDefinition {
  const funnel = BAKED_FUNNELS[funnelId];

  if (!funnel) {
    throw new Error(`Funnel '${funnelId}' is not baked.`);
  }

  return funnel;
}

function cloneFunnel<T>(value: T): T {
  if (typeof structuredClone === "function") {
    return structuredClone(value);
  }

  return JSON.parse(JSON.stringify(value));
}

export async function loadFunnelDefinition(
  funnelId: string
): Promise<FunnelDefinition> {
  const funnel = resolveBakedFunnel(funnelId);

  return cloneFunnel(funnel);
}

export function peekBakedFunnelDefinition(
  funnelId: string
): FunnelDefinition {
  return resolveBakedFunnel(funnelId);
}

export function listBakedFunnelIds(): string[] {
  return Object.keys(BAKED_FUNNELS);
}

export function listBakedFunnelScreenParams(): Array<{
  funnelId: string;
  screenId: string;
}> {
  return Object.entries(BAKED_FUNNELS).flatMap(([funnelId, funnel]) =>
    funnel.screens.map((screen) => ({
      funnelId,
      screenId: screen.id,
    }))
  );
}
