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

import { routesService } from '@/services/routes.service';

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

export function useRoutes() {
  return useQuery({
    queryKey: routeKeys.all,
    queryFn: () => routesService.getAll().then((response) => response.data),
  });
}

export function useRouteYards() {
  return useQuery({
    queryKey: routeKeys.yards,
    queryFn: () => routesService.getYards().then((response) => response.data.data),
  });
}

export function useCreateRoute() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: routesService.create,
    onSuccess: () => qc.invalidateQueries({ queryKey: routeKeys.all }),
  });
}

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

export function useDeactivateRoute() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: routesService.deactivate,
    onSuccess: (_, id) => {
      qc.invalidateQueries({ queryKey: routeKeys.all });
      qc.invalidateQueries({ queryKey: routeKeys.detail(id) });
    },
  });
}
