const express = require('express');
const router = express.Router();
const { News } = require('../models');

// 获取所有新闻列表
router.get('/', async (req, res) => {
  try {
    const { page = 1, limit = 10, category, isPublished } = req.query;
    const offset = (page - 1) * limit;
    
    const where = {};
    if (category) {
      where.category = category;
    }
    if (isPublished !== undefined) {
      where.isPublished = isPublished === 'true';
    } else {
      // 默认只显示已发布的新闻
      where.isPublished = true;
    }
    
    const news = await News.findAndCountAll({
      where,
      order: [['publishedAt', 'DESC'], ['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });
    
    res.status(200).json({
      status: 'success',
      message: '获取新闻列表成功',
      data: news.rows,
      total: news.count,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(news.count / limit)
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '获取新闻列表失败',
      error: error.message 
    });
  }
});

// 根据ID获取单条新闻
router.get('/:id', async (req, res) => {
  try {
    const news = await News.findByPk(req.params.id);
    if (!news) {
      return res.status(404).json({ 
        status: 'error',
        message: '新闻不存在',
        error: '新闻不存在' 
      });
    }
    
    // 增加浏览次数
    await news.increment('viewCount');
    
    res.status(200).json({
      status: 'success',
      message: '获取新闻详情成功',
      data: news
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '获取新闻详情失败',
      error: error.message 
    });
  }
});

// 添加新新闻
router.post('/add', async (req, res) => {
  try {
    const newsData = {
      ...req.body,
      publishedAt: req.body.publishedAt || new Date()
    };
    const news = await News.create(newsData);
    res.status(201).json({
      status: 'success',
      message: '新闻创建成功',
      data: news
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '新闻创建失败',
      error: error.message 
    });
  }
});

// 更新新闻
router.put('/:id', async (req, res) => {
  try {
    const news = await News.findByPk(req.params.id);
    if (!news) {
      return res.status(404).json({ 
        status: 'error',
        message: '新闻不存在',
        error: '新闻不存在' 
      });
    }
    await news.update(req.body);
    res.status(200).json({
      status: 'success',
      message: '新闻更新成功',
      data: news
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '新闻更新失败',
      error: error.message 
    });
  }
});

// 删除新闻
router.delete('/:id', async (req, res) => {
  try {
    const news = await News.findByPk(req.params.id);
    if (!news) {
      return res.status(404).json({ 
        status: 'error',
        message: '新闻不存在',
        error: '新闻不存在' 
      });
    }
    await news.destroy();
    res.status(200).json({ 
      status: 'success',
      message: '新闻删除成功' 
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '新闻删除失败',
      error: error.message 
    });
  }
});

// 获取新闻分类列表
router.get('/categories/list', async (req, res) => {
  try {
    const categories = await News.findAll({
      attributes: ['category'],
      where: {
        category: {
          [require('sequelize').Op.ne]: null
        }
      },
      group: ['category'],
      raw: true
    });
    
    const categoryList = categories
      .map(item => item.category)
      .filter(Boolean)
      .map((category, index) => ({
        id: index + 1,
        name: category
      }));
    
    res.status(200).json({
      status: 'success',
      message: '获取分类列表成功',
      data: categoryList
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '获取分类列表失败',
      error: error.message 
    });
  }
});

module.exports = router;
