import { Request, Response } from 'express';
import axios from "axios";
import { logger } from '../../../config/logger';
import { uploadBufferToS3, uploadFile } from '../../../services/s3Service';


// Обработчик загрузки файла в S3
export const handleFileUpload = async (req: Request, res: Response): Promise<void> => {
  if (!req.file) {
    res.status(400).json({ error: 'Нет файла для загрузки' });
    return;
  }

  const file = req.file as Express.MulterS3.File;
  const folder = req.body.folder as string;
  const resolutionId = req.body.resolutionId as string;
  const quality = Number(req.body.quality) || 80;

  try {
    // Загрузка файлв в S3
    const fileUrl = await uploadFile(folder, file, resolutionId, quality);

    res.json({ message: 'Файл успешно загружен', fileUrl });
  } catch (error) {
    logger.error(`Ошибка загрузки файла в S3: ${file.key}`);
    console.error(error);
    res.status(500).json({ error: 'Ошибка загрузки файла в S3' });
  }
};

// Обработка загрузки файла в S3 по URL изображения
export const handleUrlToImageUpload = async (req: Request, res: Response): Promise<void> => {
  const { imageUrl, folder, resolutionId, quality, filename } = req.body;

  if (!imageUrl) {
    res.status(400).json({ error: 'No image URL provided' });
    return;
  }

  try {
    // Получение изображения по URL в буфер
    const imageResponse = await axios.get(imageUrl, { responseType: 'arraybuffer' });
    const imageBuffer = Buffer.from(imageResponse.data, 'binary');

    // загрузка в S3
    const fileUrl = await uploadBufferToS3(
        imageBuffer,
        folder || 'images',
        filename,
        imageResponse.headers['content-type'],
        resolutionId,
        Number(quality) || 80
    );

    res.json({ message: 'Image successfully uploaded from URL', fileUrl });
  } catch (error) {
    logger.error(`Error uploading image from URL: ${imageUrl}`);
    console.error(error);
    res.status(500).json({ error: 'Error uploading image from URL' });
  }
};

// Handle buffer upload
export const handleBufferUpload = async (req: Request, res: Response): Promise<void> => {
  const { buffer, folder, filename, mimetype, resolutionId, quality } = req.body;

  if (!buffer) {
    res.status(400).json({ error: 'No buffer provided' });
    return;
  }

  try {
    // Convert base64 buffer to actual buffer if needed
    let actualBuffer: Buffer;
    if (typeof buffer === 'string') {
      // Assuming base64 encoded
      actualBuffer = Buffer.from(buffer, 'base64');
    } else if (Buffer.isBuffer(buffer)) {
      actualBuffer = buffer;
    } else {
      throw new Error('Invalid buffer format');
    }

    // Upload to S3
    const fileUrl = await uploadBufferToS3(
        actualBuffer,
        folder || 'buffers',
        filename,
        mimetype,
        resolutionId,
        Number(quality) || 80
    );

    res.json({ message: 'Buffer successfully uploaded', fileUrl });
  } catch (error) {
    logger.error('Error uploading buffer to S3');
    console.error(error);
    res.status(500).json({ error: 'Error uploading buffer to S3' });
  }
};