import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as bancosApi from '@/lib/api/bancos';
import { useTenantViewStore } from '@/stores/tenant-view-store';
import { useContribuyenteStore } from '@/stores/contribuyente-store';

function useBancosKey() {
  const { viewingTenantId } = useTenantViewStore();
  const { selectedContribuyenteId } = useContribuyenteStore();
  const tenantKey = viewingTenantId || 'own';
  return ['bancos', tenantKey, selectedContribuyenteId] as const;
}

export function useBancos() {
  const key = useBancosKey();
  const { selectedContribuyenteId } = useContribuyenteStore();
  return useQuery({
    queryKey: key,
    queryFn: () => bancosApi.getBancos(selectedContribuyenteId),
  });
}

export function useCreateBanco() {
  const qc = useQueryClient();
  const { selectedContribuyenteId } = useContribuyenteStore();
  return useMutation({
    mutationFn: (data: { banco: string; terminacionCuenta: string }) =>
      bancosApi.createBanco({ ...data, contribuyenteId: selectedContribuyenteId || undefined }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['bancos'] }),
  });
}

export function useDeleteBanco() {
  const qc = useQueryClient();
  const key = useBancosKey();
  return useMutation({
    mutationFn: bancosApi.deleteBanco,
    onSuccess: () => qc.invalidateQueries({ queryKey: key }),
  });
}
