import type { BotMeta, EngineStep } from "../types/flow";

const BASE = "/api";

export async function fetchMeta(): Promise<BotMeta> {
  const res = await fetch(`${BASE}/flow/meta`);
  if (!res.ok) throw new Error("Falha ao carregar bot meta");
  return res.json();
}

export async function startSession(utm?: Record<string, string>): Promise<{
  session_id: string;
  step: EngineStep;
}> {
  const res = await fetch(`${BASE}/session/start`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ utm }),
  });
  if (!res.ok) throw new Error("Falha ao iniciar sessao");
  return res.json();
}

export async function answerBlock(
  sessionId: string,
  blockId: string,
  answer: { value?: string; values?: string[]; choice_index?: number },
): Promise<{ step: EngineStep }> {
  const res = await fetch(`${BASE}/session/${sessionId}/answer`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ block_id: blockId, answer }),
  });
  if (!res.ok) throw new Error("Falha ao enviar resposta");
  return res.json();
}

export async function aiTurn(
  sessionId: string,
  blockId: string,
  message: string,
): Promise<{ reply: string; intent?: string; step?: EngineStep }> {
  const res = await fetch(`${BASE}/session/${sessionId}/ai-turn`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ block_id: blockId, message }),
  });
  if (!res.ok) throw new Error("Falha no turno de IA");
  return res.json();
}

export function parseUtm(): Record<string, string> {
  const params = new URLSearchParams(window.location.search);
  const utm: Record<string, string> = {};
  ["source", "medium", "campaign", "content", "term"].forEach((k) => {
    const v = params.get(`utm_${k}`);
    if (v) utm[k] = v;
  });
  return utm;
}
