import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { listConstancias, consultarConstancia, descargarConstanciaPdf } from '../api/constancias';
import { useTenantViewStore } from '../../stores/tenant-view-store';
import { useContribuyenteStore } from '@/stores/contribuyente-store';

export function useConstancias() {
  const viewingTenantId = useTenantViewStore((s) => s.viewingTenantId);
  const { selectedContribuyenteId } = useContribuyenteStore();
  return useQuery({
    queryKey: ['constancias', viewingTenantId, selectedContribuyenteId],
    queryFn: () => listConstancias(selectedContribuyenteId || undefined),
  });
}

export function useConsultarConstancia() {
  const qc = useQueryClient();
  const viewingTenantId = useTenantViewStore((s) => s.viewingTenantId);
  const { selectedContribuyenteId } = useContribuyenteStore();
  return useMutation({
    mutationFn: () => consultarConstancia(selectedContribuyenteId || undefined),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['constancias', viewingTenantId, selectedContribuyenteId] });
      qc.invalidateQueries({ queryKey: ['tenant-info'] });
      qc.invalidateQueries({ queryKey: ['regimenes-activos'] });
    },
  });
}

export function useDescargarConstanciaPdf() {
  return useMutation({
    mutationFn: async (id: number) => {
      const blob = await descargarConstanciaPdf(id);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `constancia_${id}.pdf`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    },
  });
}
