const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const { upload, getFileUrls } = require('../middleware/upload');
const { VenueImage } = require('../models');

// 获取场地图片列表
router.get('/venue-images', auth, async (req, res) => {
  try {
    const { activityId } = req.query;
    const images = await VenueImage.findAll({
      where: { activityId },
      order: [['sortOrder', 'ASC'], ['id', 'ASC']],
      raw: true
    });
    res.json(images);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 上传场地图片
router.post('/venue-images', auth, upload.single('image'), async (req, res) => {
  try {
    const { activityId, sortOrder } = req.body;
    
    if (!req.file) {
      return res.status(400).json({ error: '请选择图片' });
    }
    
    const [uploaded] = getFileUrls([req.file]);
    const image = await VenueImage.create({
      activityId,
      image: uploaded.url,
      sortOrder: sortOrder || 0
    });
    
    res.json(image);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新场地图片排序
router.put('/venue-images/:id', auth, async (req, res) => {
  try {
    const { sortOrder } = req.body;
    await VenueImage.update({ sortOrder }, { where: { id: req.params.id } });
    const image = await VenueImage.findByPk(req.params.id);
    res.json(image);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除场地图片
router.delete('/venue-images/:id', auth, async (req, res) => {
  try {
    await VenueImage.destroy({ where: { id: req.params.id } });
    res.json({ message: '删除成功' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
