import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";

export type AccountingSystem = "buildium" | "zoho" | "platform";

/**
 * Resolves which Chart of Accounts system an association uses.
 * - 'zoho'    if the association has a zoho_organization_id
 * - 'buildium' otherwise (default — including when no association is selected)
 *
 * Source of truth: the SQL helper public.get_association_accounting_system().
 * We replicate the logic client-side via a single lightweight query.
 */
export function useAssociationAccountingSystem(associationId?: string | null) {
  const [system, setSystem] = useState<AccountingSystem>("buildium");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;

    if (!associationId) {
      setSystem("buildium");
      setLoading(false);
      return;
    }

    setLoading(true);
    (async () => {
      const { data, error } = await supabase
        .from("associations")
        .select("*")
        .eq("id", associationId)
        .maybeSingle();

      if (cancelled) return;
      if (error) {
        console.error("[accounting] failed to resolve accounting system", error);
        setSystem("buildium");
        setLoading(false);
        return;
      }

      const row = data as any;
      const explicit = row?.accounting_system as AccountingSystem | undefined;
      if (explicit === "zoho" || explicit === "buildium" || explicit === "platform") {
        setSystem(explicit);
      } else {
        // Legacy fallback for rows predating the accounting_system column
        const zoho = row?.zoho_organization_id && String(row.zoho_organization_id).trim() !== "";
        setSystem(zoho ? "zoho" : "buildium");
      }
      setLoading(false);
    })().catch((error) => {
      if (!cancelled) {
        console.error("[accounting] failed to resolve accounting system", error);
        setSystem("buildium");
        setLoading(false);
      }
    });

    return () => {
      cancelled = true;
    };
  }, [associationId]);

  return { system, loading };
}
