import { Router, Request, Response, NextFunction } from 'express';
import { uploadVideo, uploadImage, uploadCover } from '../middleware/upload.js';
import { authenticate } from '../middleware/auth.js';
import { asyncHandler, AppError } from '../middleware/error.js';
import { ERROR_CODES, HTTP_STATUS } from '@media-manager/shared';

const router = Router();

router.use(authenticate);

// 包装 multer 错误处理
const handleMulterError = (
  uploadFn: (req: Request, res: Response, next: NextFunction) => void
) => {
  return (req: Request, res: Response, next: NextFunction) => {
    uploadFn(req, res, (err: unknown) => {
      if (err) {
        if ((err as { code?: string }).code === 'LIMIT_FILE_SIZE') {
          return next(new AppError('文件大小超出限制', HTTP_STATUS.BAD_REQUEST, ERROR_CODES.VIDEO_TOO_LARGE));
        }
        return next(err);
      }
      next();
    });
  };
};

// 上传视频
router.post(
  '/video',
  handleMulterError(uploadVideo),
  asyncHandler(async (req, res) => {
    if (!req.file) {
      throw new AppError('未上传文件', HTTP_STATUS.BAD_REQUEST, ERROR_CODES.VALIDATION);
    }
    
    res.json({
      success: true,
      data: {
        filename: req.file.filename,
        originalname: req.file.originalname,
        path: `/uploads/videos/${req.file.filename}`,
        size: req.file.size,
        mimetype: req.file.mimetype,
      },
    });
  })
);

// 上传图片
router.post(
  '/image',
  handleMulterError(uploadImage),
  asyncHandler(async (req, res) => {
    if (!req.file) {
      throw new AppError('未上传文件', HTTP_STATUS.BAD_REQUEST, ERROR_CODES.VALIDATION);
    }
    
    res.json({
      success: true,
      data: {
        filename: req.file.filename,
        originalname: req.file.originalname,
        path: `/uploads/images/${req.file.filename}`,
        size: req.file.size,
        mimetype: req.file.mimetype,
      },
    });
  })
);

// 上传封面
router.post(
  '/cover',
  handleMulterError(uploadCover),
  asyncHandler(async (req, res) => {
    if (!req.file) {
      throw new AppError('未上传文件', HTTP_STATUS.BAD_REQUEST, ERROR_CODES.VALIDATION);
    }
    
    res.json({
      success: true,
      data: {
        filename: req.file.filename,
        originalname: req.file.originalname,
        path: `/uploads/covers/${req.file.filename}`,
        size: req.file.size,
        mimetype: req.file.mimetype,
      },
    });
  })
);

export default router;
