import { useEffect, useState } from "react";
import { ensureAccountingCompany } from "@/lib/accountingClient";

/**
 * Resolves (and provisions on demand) the accounting.companies row
 * for the given association. Returns the company_id once ready.
 */
export function useAccountingCompany(associationId?: string | null) {
  const [companyId, setCompanyId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;
    if (!associationId) { setCompanyId(null); setError(null); setLoading(false); return; }
    setLoading(true);
    setError(null);
    ensureAccountingCompany(associationId).then((result) => {
      if (!cancelled) { setCompanyId(result.companyId); setError(result.error); setLoading(false); }
    }).catch((err) => {
      if (!cancelled) { setCompanyId(null); setError(err?.message || "Accounting setup is not ready."); setLoading(false); }
    });
    return () => { cancelled = true; };
  }, [associationId]);

  return { companyId, loading, error };
}