const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { success, fail } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');

const uploadDir = path.join(__dirname, '..', '..', 'uploads');
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, uploadDir),
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    cb(null, `${Date.now()}${Math.random().toString(36).slice(2,8)}${ext}`);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    // 🔒 [安全] 仅允许图片扩展名，禁止危险扩展(html/svg/php等可执行/脚本)
    const allowedExt = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
    const ext = path.extname(file.originalname).toLowerCase();
    if (!allowedExt.includes(ext)) return cb(null, false);
    // MIME 校验（图片类型）
    const imgMime = /^image\/(jpeg|png|gif|webp)$/;
    if (file.mimetype && !imgMime.test(file.mimetype)) return cb(null, false);
    cb(null, true);
  }
});

// 验证文件内容的真实类型(magic bytes)，防止伪造扩展名上传可执行文件
function isValidImageFile(file) {
  if (!file || !file.path) return false;
  const header = fs.readFileSync(file.path).subarray(0, 12);
  const b = header;
  return (b[0] === 0xFF && b[1] === 0xD8)                    // JPEG
    || (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4E && b[3] === 0x47) // PNG
    || b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46     // GIF
    || (b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46); // RIFF (webp)
}

// 上传图片
router.post('/image', authAdmin, upload.single('file'), (req, res) => {
  if (!req.file) return res.json(fail('请选择图片'));
  // 🔒 [安全] 校验真实文件类型(magic bytes)，防止伪装图片上传可执行文件
  if (!isValidImageFile(req.file)) {
    fs.unlinkSync(req.file.path); // 清理非法文件
    return res.json(fail('文件内容不是有效图片'));
  }
  const url = `/uploads/${req.file.filename}`;
  return res.json(success({ url, filename: req.file.filename }, '上传成功'));
});

// 多图上传
router.post('/images', authAdmin, upload.array('files', 10), (req, res) => {
  if (!req.files || !req.files.length) return res.json(fail('请选择图片'));
  // 🔒 [安全] 逐文件校验真实类型(magic bytes)，防伪装扩展名落地可执行文件，非法文件清理
  for (const f of req.files) {
    if (!isValidImageFile(f)) {
      try { fs.unlinkSync(f.path); } catch (e) {}
      return res.json(fail('文件内容不是有效图片: ' + (f.filename || '')));
    }
  }
  const urls = req.files.map(f => ({ url: `/uploads/${f.filename}`, filename: f.filename }));
  return res.json(success(urls, '上传成功'));
});

module.exports = router;
