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

/**
 * Helper that scopes Supabase queries to the `accounting` schema where
 * the Secure Ledger tables live.
 */
export const accounting = (supabase as any).schema("accounting");

export type AccountingCompanyResult = {
  companyId: string | null;
  error: string | null;
};

const withTimeout = <T,>(promise: Promise<T>, ms = 12000): Promise<T> =>
  Promise.race([
    promise,
    new Promise<T>((_, reject) => window.setTimeout(() => reject(new Error("Accounting setup request timed out.")), ms)),
  ]);

/**
 * Ensure an `accounting.companies` row exists for the given association id
 * (auto-provisioning when the association switches to the "platform"
 * accounting system). Returns the resolved company_id.
 */
export async function ensureAccountingCompany(associationId: string): Promise<AccountingCompanyResult> {
  if (!associationId) return { companyId: null, error: null };
  const { data, error } = await withTimeout<any>(
    (supabase as any).schema("accounting").rpc("ensure_company_for_association", {
      _association_id: associationId,
    })
  );
  if (error) {
    // Board members (and other non-accounting-staff) can't provision a company,
    // but may read their association's existing one. Fall back to the read-only
    // resolver before surfacing an error.
    try {
      const { data: roData, error: roErr } = await withTimeout<any>(
        (supabase as any).schema("accounting").rpc("company_id_for_association", {
          _association_id: associationId,
        })
      );
      if (!roErr && roData) return { companyId: roData as string, error: null };
    } catch { /* ignore — fall through to the original error */ }

    console.error("[accounting] ensure_company_for_association failed", error);
    const missingRpc = error.code === "PGRST202";
    return {
      companyId: null,
      error: missingRpc
        ? "The accounting setup function is missing from the connected backend. Deploy the accounting schema bundle, then refresh."
        : error.message || "Accounting setup is not ready.",
    };
  }
  return { companyId: (data as string) ?? null, error: null };
}