import { supabase } from "@/integrations/supabase/client";

/**
 * Client wrappers around the `plaid` Supabase Edge Function (ACMACC).
 * The function holds PLAID_CLIENT_ID/SECRET (server secrets) and writes the
 * accounting schema with the service role. All calls require an authenticated
 * user (verify_jwt).
 */
async function invoke<T>(body: Record<string, unknown>): Promise<T> {
  const { data, error } = await supabase.functions.invoke("plaid", { body });
  if (error) {
    const ctx: any = (error as any).context;
    let msg = error.message;
    try { const b = ctx && (await ctx.json?.()); if (b?.error) msg = b.error; } catch { /* ignore */ }
    throw new Error(msg || "Plaid request failed.");
  }
  if ((data as any)?.error) throw new Error((data as any).error);
  return data as T;
}

export function createLinkToken(userId: string, companyId: string) {
  return invoke<{ link_token: string }>({ action: "create_link_token", userId, companyId });
}

export function exchangePlaidToken(input: {
  publicToken: string;
  companyId: string;
  accountId: string;
  plaidAccountId: string;
  institutionName?: string;
  institutionId?: string;
  mask?: string;
}) {
  return invoke<{ success: boolean; institution: string }>({ action: "exchange", ...input });
}

export function syncPlaidTransactions(companyId: string, accountId?: string) {
  return invoke<{ added: number; modified: number; removed: number; errors: string[] }>({ action: "sync", companyId, accountId });
}

export function disconnectPlaid(accountId: string) {
  return invoke<{ success: boolean }>({ action: "disconnect", accountId });
}
