// Client helpers for the Delta Exchange authenticated proxy at
// /api/delta/account. Credentials are held in localStorage on the user's
// browser and posted to our server route per-request; the server signs the
// call to Delta and returns the balance.

export type DeltaRegion = "india" | "global";

export interface DeltaCreds {
  api_key: string;
  api_secret: string;
  region: DeltaRegion;
  label?: string;
}

export interface DeltaAccountResponse {
  connected: boolean;
  error?: string;
  hint?: string;
  status?: number;
  account_id?: string;
  email?: string;
  balance?: number;
  currency?: string;
  balances?: { asset: string; balance: number; available: number }[];
  permissions?: string[];
  region?: DeltaRegion;
  last_synced_at?: string;
}

const CREDS_KEY = "delta-terminal-creds";

export function loadCreds(): DeltaCreds | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = window.localStorage.getItem(CREDS_KEY);
    return raw ? (JSON.parse(raw) as DeltaCreds) : null;
  } catch {
    return null;
  }
}

export function saveCreds(c: DeltaCreds) {
  if (typeof window === "undefined") return;
  window.localStorage.setItem(CREDS_KEY, JSON.stringify(c));
  window.dispatchEvent(new Event("delta-creds-changed"));
}

export function clearCreds() {
  if (typeof window === "undefined") return;
  window.localStorage.removeItem(CREDS_KEY);
  window.dispatchEvent(new Event("delta-creds-changed"));
}

export async function fetchDeltaAccount(creds: DeltaCreds): Promise<DeltaAccountResponse> {
  const res = await fetch("/api/delta/account", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(creds),
  });
  return (await res.json()) as DeltaAccountResponse;
}
