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

export const cargoKeys = {
  all: ['cargoes'] as const,
  byContainer: (containerId: string) => [...cargoKeys.all, 'container', containerId] as const,
  details: () => [...cargoKeys.all, 'detail'] as const,
  detail: (id: string) => [...cargoKeys.details(), id] as const,
};

export function useCargoes() {
  return useQuery({ queryKey: cargoKeys.all, queryFn: () => cargoService.getAll().then(res => res.data) });
}

export const useGetCargoes = useCargoes;

export function useCargoesByContainer(containerId: string) {
  return useQuery({ queryKey: cargoKeys.byContainer(containerId), queryFn: () => cargoService.getByContainer(containerId).then(res => res.data), enabled: !!containerId });
}

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

export const useGetCargo = useCargo;

export function useCreateCargo() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: cargoService.create, onSuccess: () => qc.invalidateQueries({ queryKey: cargoKeys.all }) });
}

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

export function useDeleteCargo() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: cargoService.delete, onSuccess: () => qc.invalidateQueries({ queryKey: cargoKeys.all }) });
}

export function useLoadCargo() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, quantity, weight, volume }: any) => cargoService.load(id, quantity, weight, volume),
    onSuccess: (_, { id }) => qc.invalidateQueries({ queryKey: cargoKeys.all })
  });
}

export function useDeliverCargo() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => cargoService.deliver(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: cargoKeys.all })
  });
}

export function useUnloadCargo() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => cargoService.unload(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: cargoKeys.all })
  });
}
