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

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

export const usePostUploadPhotoMutation = () => {
  return useMutation<
    PostUploadTempFileReturn,
    BaseAxiosError,
    UseUploadPhotoVariables,
    PostUploadTempFileReturn
  >({
    mutationKey: eventsQueryKeys.uploadPhoto(),
    mutationFn: async (variables) => {
      const { token, event_id, file, onUploadProgress } = variables;

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

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

      return response.data;
    }
  });
};
