'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuthStore } from '@/stores/auth-store';
import * as api from '@/lib/api/contribuyentes';

export function useContribuyentes() {
  const user = useAuthStore((s) => s.user);
  return useQuery({
    queryKey: ['contribuyentes', user?.tenantId],
    queryFn: () => api.getContribuyentes().then((r) => r.data),
    enabled: !!user,
  });
}

export function useContribuyente(id: string | null) {
  const user = useAuthStore((s) => s.user);
  return useQuery({
    queryKey: ['contribuyente', id, user?.tenantId],
    queryFn: () => api.getContribuyente(id!),
    enabled: !!user && !!id,
  });
}

export function useCreateContribuyente() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.createContribuyente,
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['contribuyentes'] }); },
  });
}

export function useUpdateContribuyente() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<api.CreateContribuyenteData> }) =>
      api.updateContribuyente(id, data),
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['contribuyentes'] }); },
  });
}

export function useDeactivateContribuyente() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.deactivateContribuyente,
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['contribuyentes'] }); },
  });
}
