import { useMutation } from '@tanstack/react-query';
import { AxiosProgressEvent, AxiosRequestConfig } from 'axios';
import { eventsQueryKeys } from '../events-query-keys';
import { eventsApi, PostUploadTempFileReturn, type PostUploadTemp } from '../events-api';
import { type BaseAxiosError } from '../../../../types';

export interface UseUploadTempFileVariables extends PostUploadTemp {
  onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
}

export const usePostUploadTempFileMutation = () => {
  return useMutation<
    PostUploadTempFileReturn,
    BaseAxiosError,
    UseUploadTempFileVariables,
    PostUploadTempFileReturn
  >({
    mutationKey: eventsQueryKeys.uploadTempFile(),
    mutationFn: async (variables) => {
      const { token, file, onUploadProgress } = variables;

      const config: AxiosRequestConfig = {
        onUploadProgress: (progressEvent: AxiosProgressEvent) => {
          if (onUploadProgress) {
            onUploadProgress(progressEvent);
          }
        }
      };

      const response = await eventsApi.uploadTempFile({ token, file }, config);

      return response.data;
    }
  });
};
