import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

import { locomotivesService } from '@/services/locomotives.service';

export const locomotiveKeys = {
  all: ['locomotives'] as const,
  details: () => [...locomotiveKeys.all, 'detail'] as const,
  detail: (id: string) => [...locomotiveKeys.details(), id] as const,
};

export function useLocomotives() {
  return useQuery({
    queryKey: locomotiveKeys.all,
    queryFn: () => locomotivesService.getAll().then((response) => response.data),
  });
}

export function useCreateLocomotive() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: locomotivesService.create,
    onSuccess: () => qc.invalidateQueries({ queryKey: locomotiveKeys.all }),
  });
}

export function useUpdateLocomotive() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) =>
      locomotivesService.update(id, data),
    onSuccess: (_, { id }) => {
      qc.invalidateQueries({ queryKey: locomotiveKeys.all });
      qc.invalidateQueries({ queryKey: locomotiveKeys.detail(id) });
    },
  });
}

export function useDecommissionLocomotive() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: locomotivesService.decommission,
    onSuccess: (_, id) => {
      qc.invalidateQueries({ queryKey: locomotiveKeys.all });
      qc.invalidateQueries({ queryKey: locomotiveKeys.detail(id) });
    },
  });
}
