import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getMisTareas } from '../api/tareas-mis';
import { apiClient } from '../api/client';

export function useMisTareas() {
  return useQuery({
    queryKey: ['tareas-mis-tareas'],
    queryFn: getMisTareas,
  });
}

export function useCompletarTareaPeriodo() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (periodoId: string) =>
      apiClient.post(`/tareas/periodo/${periodoId}/completar`).then(r => r.data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tareas-mis-tareas'] });
      qc.invalidateQueries({ queryKey: ['tareas'] });
    },
    onError: (err: any) => {
      alert(err.response?.data?.message || 'No se pudo marcar como completada');
    },
  });
}

export function useDescompletarTareaPeriodo() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (periodoId: string) =>
      apiClient.delete(`/tareas/periodo/${periodoId}/completar`).then(r => r.data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tareas-mis-tareas'] });
      qc.invalidateQueries({ queryKey: ['tareas'] });
    },
  });
}
