// frontend/lib/proactive/api.ts — 능동 카드 + 워커 수동 트리거
import type {
  ProactiveCard,
  ProactiveAcceptResult,
  WorkerRunResult,
} from "@/lib/types";

const BASE = process.env.NEXT_PUBLIC_API_BASE ?? "http://localhost:31800";

export async function getProactive(signal?: AbortSignal): Promise<ProactiveCard[]> {
  const res = await fetch(`${BASE}/api/proactive`, { signal, cache: "no-store" });
  if (!res.ok) throw new Error(`proactive ${res.status}`);
  return res.json();
}

export async function acceptProactive(id: string): Promise<ProactiveAcceptResult> {
  const res = await fetch(`${BASE}/api/proactive/${id}/accept`, { method: "POST" });
  if (!res.ok) throw new Error(`proactive accept ${res.status}`);
  return res.json();
}

export async function dismissProactive(id: string): Promise<{ ok: boolean }> {
  const res = await fetch(`${BASE}/api/proactive/${id}/dismiss`, { method: "POST" });
  if (!res.ok) throw new Error(`proactive dismiss ${res.status}`);
  return res.json();
}

export async function runWorkerJob(
  job: string,
  payload?: Record<string, unknown>,
): Promise<WorkerRunResult> {
  const res = await fetch(`${BASE}/api/worker/run/${job}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload ?? {}),
  });
  if (!res.ok) throw new Error(`worker ${job} ${res.status}`);
  return res.json();
}
