import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getOpiniones, descargarOpinionPdf, consultarOpinion } from '../api/documentos';
import { useTenantViewStore } from '../../stores/tenant-view-store';
import { useContribuyenteStore } from '@/stores/contribuyente-store';

export function useOpiniones() {
  const viewingTenantId = useTenantViewStore((s) => s.viewingTenantId);
  const { selectedContribuyenteId } = useContribuyenteStore();

  return useQuery({
    queryKey: ['opiniones', viewingTenantId, selectedContribuyenteId],
    queryFn: () => getOpiniones(selectedContribuyenteId || undefined),
  });
}

export function useConsultarOpinion() {
  const queryClient = useQueryClient();
  const viewingTenantId = useTenantViewStore((s) => s.viewingTenantId);
  const { selectedContribuyenteId } = useContribuyenteStore();

  return useMutation({
    mutationFn: () => consultarOpinion(selectedContribuyenteId || undefined),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['opiniones', viewingTenantId, selectedContribuyenteId] });
    },
  });
}

export function useDescargarPdf() {
  return useMutation({
    mutationFn: async (id: number) => {
      const blob = await descargarOpinionPdf(id);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `opinion_cumplimiento_${id}.pdf`;
      a.click();
      URL.revokeObjectURL(url);
    },
  });
}
