// frontend/lib/connectors/api.ts — connectorsApi (목록/동기화/해제/임포트/OAuth)
import type { ConnectorStatus, SyncResult, ImportResult, OAuthStart } from "@/lib/types";

async function ok<T>(r: Response): Promise<T> {
  if (!r.ok) throw new Error(`${r.status} ${r.statusText}`);
  return r.json() as Promise<T>;
}

export const connectorsApi = {
  list: (domain = "") =>
    fetch(domain ? `/api/connectors?domain=${encodeURIComponent(domain)}` : "/api/connectors", {
      cache: "no-store",
    }).then((r) => ok<ConnectorStatus[]>(r)),

  sync: (id: string) =>
    fetch(`/api/connectors/${id}/sync`, { method: "POST" }).then((r) => ok<SyncResult>(r)),

  syncAll: () =>
    fetch("/api/connectors/sync-all", { method: "POST" }).then((r) => ok<SyncResult[]>(r)),

  disconnect: (id: string) =>
    fetch(`/api/connectors/${id}/disconnect`, { method: "POST" }).then((r) =>
      ok<ConnectorStatus>(r),
    ),

  importFile: (id: string, file: File) => {
    const fd = new FormData();
    fd.append("file", file);
    return fetch(`/api/connectors/${id}/import`, {
      method: "POST",
      body: fd,
    }).then((r) => ok<ImportResult>(r));
  },

  oauthStart: (domain: string, provider: string) =>
    fetch(
      `/api/connectors/oauth/start?domain=${encodeURIComponent(domain)}&provider=${encodeURIComponent(provider)}`,
    ).then((r) => ok<OAuthStart>(r)),
};
