import axios from '../utils/api';
import {ImageResolution, UploadedImage} from '../types/image';

export async function uploadImageToS3(file: File, resolution: ImageResolution, articleId: string, onProgress?: (progress: number) => void): Promise<UploadedImage> {

  const formData = new FormData();
  formData.append('file', file);
  formData.append('resolutionId', resolution.id);
  formData.append('folder', 'articles/' + articleId + '/gallery');

  // Загрузка файла изображения в хранилище S3
  const response = await axios.post('/images/upload-url', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': `Bearer ${localStorage.getItem('token')}`, // Передача токена аутентификации
    },
    onUploadProgress: (progressEvent) => {
      if (progressEvent.total) {
        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress?.(progress);
      }
    }
  });

  return {
    id: '',
    url: response.data?.fileUrl,
    width: resolution.width,
    height: resolution.height,
    size: 102400,
    format: 'webp'
  };
}