const sharp = require('sharp');
const path = require('path');
const fs = require('fs').promises;
const { uploadDir } = require('../middleware/upload');
const logger = require('../config/logger');

// 图片处理阈值：小于此大小的图片不进行压缩处理（500KB）
const SKIP_PROCESSING_SIZE = 500 * 1024;

/**
 * Upload and process image
 * POST /api/v1/upload/image
 */
const uploadImage = async (req, res, next) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        code: 400,
        message: 'No file uploaded',
        data: null,
      });
    }

    const originalPath = req.file.path;
    const originalSize = req.file.size;
    const originalExt = path.extname(req.file.originalname).toLowerCase();
    
    // Generate unique filename
    const timestamp = Date.now();
    const randomString = Math.random().toString(36).substring(2, 15);
    
    // 对于小图片或已经是jpg/jpeg格式的小图片，跳过处理直接使用
    const isSmallImage = originalSize < SKIP_PROCESSING_SIZE;
    const isJpeg = ['.jpg', '.jpeg'].includes(originalExt);
    
    if (isSmallImage && isJpeg) {
      // 小的JPEG图片直接重命名使用，不进行处理
      const newFilename = `${timestamp}_${randomString}.jpg`;
      const newPath = path.join(uploadDir, newFilename);
      
      try {
        await fs.rename(originalPath, newPath);
      } catch (renameError) {
        // 如果重命名失败（跨分区），则复制后删除
        await fs.copyFile(originalPath, newPath);
        await fs.unlink(originalPath).catch(() => {});
      }
      
      const imageUrl = `/uploads/${newFilename}`;
      
      logger.info('Image uploaded (skipped processing)', {
        originalName: req.file.originalname,
        filename: newFilename,
        size: originalSize,
      });

      return res.status(200).json({
        code: 0,
        message: 'Image uploaded successfully',
        data: {
          url: imageUrl,
          filename: newFilename,
          originalName: req.file.originalname,
          size: originalSize,
        },
      });
    }
    
    // 需要处理的图片
    const processedFilename = `${timestamp}_${randomString}.jpg`;
    const processedPath = path.join(uploadDir, processedFilename);
    
    // Ensure output path is different from input path
    if (processedPath === originalPath) {
      throw new Error('Output path cannot be the same as input path');
    }

    try {
      // Process image with Sharp - 使用更快的设置
      const sharpInstance = sharp(originalPath, {
        failOnError: false, // 不因为小错误而失败
        limitInputPixels: false, // 不限制输入像素
      });
      
      await sharpInstance
        .resize(1200, 1200, {
          fit: 'inside',
          withoutEnlargement: true,
        })
        .jpeg({
          quality: 80, // 稍微降低质量以加快处理速度
          progressive: false, // 关闭渐进式以加快处理
          mozjpeg: false, // 不使用mozjpeg以加快速度
        })
        .toFile(processedPath);

      // Destroy sharp instance to release file handles
      sharpInstance.destroy();

      // Delete original file - 异步删除，不等待
      fs.unlink(originalPath).catch(unlinkError => {
        logger.warn('Could not delete original file', { 
          path: originalPath,
          error: unlinkError.message 
        });
      });

      // Return relative path for the image
      const imageUrl = `/uploads/${processedFilename}`;

      logger.info('Image uploaded and processed successfully', {
        originalName: req.file.originalname,
        processedFilename,
        originalSize,
      });

      res.status(200).json({
        code: 0,
        message: 'Image uploaded successfully',
        data: {
          url: imageUrl,
          filename: processedFilename,
          originalName: req.file.originalname,
          size: req.file.size,
        },
      });
    } catch (processingError) {
      // Clean up file if processing fails
      fs.unlink(originalPath).catch(() => {});
      throw processingError;
    }
  } catch (error) {
    logger.error('Image upload error', { error: error.message });
    next(error);
  }
};

module.exports = {
  uploadImage,
};
