import { accounting } from "@/lib/accountingClient";

export const UNDEPOSITED_FUNDS_NAME = "Undeposited Funds";

/** Ensure the company has an "Undeposited Funds" system account; return its id. */
export async function ensureUndepositedFunds(companyId: string): Promise<string> {
  const { data: existing } = await accounting
    .from("accounts")
    .select("id")
    .eq("company_id", companyId)
    .eq("name", UNDEPOSITED_FUNDS_NAME)
    .maybeSingle();
  if (existing?.id) return existing.id;

  const { data, error } = await accounting
    .from("accounts")
    .insert({
      company_id: companyId,
      name: UNDEPOSITED_FUNDS_NAME,
      code: "1499",
      type: "asset",
      is_bank: false,
      is_system: true,
      description: "Holding account for received payments awaiting deposit",
    })
    .select("id")
    .single();
  if (error || !data) throw new Error(error?.message ?? "Failed to create Undeposited Funds account");
  return data.id;
}
