import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as cfdiApi from '@/lib/api/cfdi';
import type { CfdiFilters } from '@horux/shared';
import type { CreateCfdiData } from '@/lib/api/cfdi';
import { useContribuyenteStore } from '@/stores/contribuyente-store';

export function useCfdis(filters: CfdiFilters) {
  const { selectedContribuyenteId } = useContribuyenteStore();
  const filtersWithContribuyente: CfdiFilters = {
    ...filters,
    contribuyenteId: selectedContribuyenteId || undefined,
  };
  return useQuery({
    queryKey: ['cfdis', filters, selectedContribuyenteId],
    queryFn: () => cfdiApi.getCfdis(filtersWithContribuyente),
  });
}

export function useCfdi(id: string) {
  return useQuery({
    queryKey: ['cfdi', id],
    queryFn: () => cfdiApi.getCfdiById(id),
    enabled: !!id,
  });
}

export function useResumenCfdi(año?: number, mes?: number) {
  const { selectedContribuyenteId } = useContribuyenteStore();
  return useQuery({
    queryKey: ['cfdi-resumen', año, mes, selectedContribuyenteId],
    queryFn: () => cfdiApi.getResumenCfdi(año, mes, selectedContribuyenteId || undefined),
  });
}

export function useCreateCfdi() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: CreateCfdiData) => cfdiApi.createCfdi(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cfdis'] });
      queryClient.invalidateQueries({ queryKey: ['cfdi-resumen'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
    },
  });
}

export function useCreateManyCfdis() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (cfdis: CreateCfdiData[]) => cfdiApi.createManyCfdis(cfdis),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cfdis'] });
      queryClient.invalidateQueries({ queryKey: ['cfdi-resumen'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
    },
  });
}

export function useDeleteCfdi() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => cfdiApi.deleteCfdi(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cfdis'] });
      queryClient.invalidateQueries({ queryKey: ['cfdi-resumen'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
    },
  });
}
