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

export const containerKeys = {
  all: ['containers'] as const,
  byWagon: (wagonId: string) => [...containerKeys.all, 'wagon', wagonId] as const,
  details: () => [...containerKeys.all, 'detail'] as const,
  detail: (id: string) => [...containerKeys.details(), id] as const,
};

export function useContainers() {
  return useQuery({ queryKey: containerKeys.all, queryFn: () => containerService.getAll().then(res => res.data) });
}

export const useGetContainers = useContainers;

export function useContainersByWagon(wagonId: string) {
  return useQuery({ queryKey: containerKeys.byWagon(wagonId), queryFn: () => containerService.getByWagon(wagonId).then(res => res.data), enabled: !!wagonId });
}

export function useContainer(id: string) {
  return useQuery({ queryKey: containerKeys.detail(id), queryFn: () => containerService.getById(id).then(res => res.data), enabled: !!id });
}

export const useGetContainer = useContainer;

export function useCreateContainer() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: containerService.create, onSuccess: () => qc.invalidateQueries({ queryKey: containerKeys.all }) });
}

export function useUpdateContainer() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: ({ id, data }: any) => containerService.update(id, data), onSuccess: (_, { id }) => {
    qc.invalidateQueries({ queryKey: containerKeys.all });
    qc.invalidateQueries({ queryKey: containerKeys.detail(id) });
  } });
}

export function useDeleteContainer() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: containerService.delete, onSuccess: () => qc.invalidateQueries({ queryKey: containerKeys.all }) });
}

export function useAssignContainerToWagon() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ containerId, wagonId, position }: any) => containerService.assignToWagon(containerId, wagonId, position),
    onSuccess: (_, { wagonId }) => qc.invalidateQueries({ queryKey: containerKeys.byWagon(wagonId) })
  });
}

export function useUnassignContainer() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: containerService.unassign,
    onSuccess: () => qc.invalidateQueries({ queryKey: containerKeys.all })
  });
}
