import { useAssociation } from "@/contexts/AssociationContext";
import { useAccountingCompany } from "@/hooks/useAccountingCompany";

/**
 * The accounting module's single source for the current company scope.
 *
 * In the original standalone app this came from `useCompany().current.id`
 * (a per-user company picker). In avria, accounting is multi-tenant by HOA
 * association: the selected association resolves (and auto-provisions) an
 * `accounting.companies` row, whose id scopes every accounting query.
 *
 * Every ported accounting page uses this instead of the old `useCompany`.
 */
export function useCompanyId(override?: { id: string; name?: string } | null) {
  const { selectedAssociation } = useAssociation() as {
    selectedAssociation: { id: string; name?: string } | null;
  };
  // When an explicit association is supplied (e.g. the Financial Overview /
  // Reports wrappers, or a board scope), it takes precedence over the global
  // association picker.
  const active = override ?? selectedAssociation;
  const associationId = active?.id ?? null;
  const { companyId, loading, error } = useAccountingCompany(associationId);
  return {
    associationId,
    associationName: active?.name ?? null,
    companyId,
    loading,
    error,
  };
}
