import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as calendarioApi from '../api/calendario';
import { useTenantViewStore } from '@/stores/tenant-view-store';
import { useContribuyenteStore } from '@/stores/contribuyente-store';
import type { EventoCreate, EventoUpdate } from '@horux/shared';

function useTenantKey() {
  const { viewingTenantId } = useTenantViewStore();
  return viewingTenantId || 'own';
}

export function useEventos(año: number) {
  const tenantKey = useTenantKey();
  const { selectedContribuyenteId } = useContribuyenteStore();
  return useQuery({
    queryKey: ['calendario', tenantKey, año, selectedContribuyenteId],
    queryFn: () => calendarioApi.getEventos(año, selectedContribuyenteId),
  });
}

export function useProximosEventos(dias = 30) {
  const tenantKey = useTenantKey();
  return useQuery({
    queryKey: ['calendario-proximos', tenantKey, dias],
    queryFn: () => calendarioApi.getProximos(dias),
  });
}

export function useCreateEvento() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: EventoCreate) => calendarioApi.createEvento(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['calendario'] });
    },
  });
}

export function useUpdateEvento() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: EventoUpdate }) => calendarioApi.updateEvento(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['calendario'] });
    },
  });
}

export function useDeleteEvento() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => calendarioApi.deleteEvento(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['calendario'] });
    },
  });
}
