const express = require('express');
const { body, validationResult } = require('express-validator');
const db = require('../config/database');
const { auth, authorize } = require('../middleware/auth');

const router = express.Router();

router.get('/', auth, (req, res) => {
  const { page = 1, limit = 20, industry, search } = req.query;
  const offset = (page - 1) * limit;
  
  let query = 'SELECT * FROM industry_news WHERE 1=1';
  const params = [];
  
  if (industry) {
    query += ' AND industry = ?';
    params.push(industry);
  }
  
  if (search) {
    query += ' AND (title LIKE ? OR summary LIKE ?)';
    const searchTerm = `%${search}%`;
    params.push(searchTerm, searchTerm);
  }
  
  query += ' ORDER BY published_at DESC, created_at DESC LIMIT ? OFFSET ?';
  params.push(parseInt(limit), offset);
  
  const news = db.prepare(query).all(...params);
  
  let countQuery = query.replace(/SELECT.*FROM/, 'SELECT COUNT(*) as total FROM').replace(/ORDER BY.*$/, '').replace(/ LIMIT \? OFFSET \?$/, '');
  const countParams = params.slice(0, -2);
  const countResult = db.prepare(countQuery).get(...countParams);
  
  res.json({
    news,
    pagination: {
      page: parseInt(page),
      limit: parseInt(limit),
      total: countResult?.total || 0
    }
  });
});

router.get('/:id', auth, (req, res) => {
  const news = db.prepare('SELECT * FROM industry_news WHERE id = ?').get(req.params.id);
  if (!news) {
    return res.status(404).json({ message: '新闻不存在' });
  }
  res.json({ news });
});

router.post('/', auth, authorize('admin', 'investment_manager'), [
  body('title').notEmpty().withMessage('标题不能为空'),
  body('industry').notEmpty().withMessage('行业不能为空')
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const { title, source, industry, summary, content, url, publishedAt } = req.body;

  const result = db.prepare(
    'INSERT INTO industry_news (title, source, industry, summary, content, url, published_at) VALUES (?, ?, ?, ?, ?, ?, ?)'
  ).run(title, source || '', industry, summary || '', content || '', url || '', publishedAt || new Date().toISOString());

  res.status(201).json({ message: '新闻创建成功', newsId: result.lastInsertRowid });
});

router.put('/:id', auth, authorize('admin', 'investment_manager'), (req, res) => {
  const { title, source, industry, summary, content, url, publishedAt } = req.body;

  const updates = [];
  const params = [];

  if (title !== undefined) updates.push('title = ?'), params.push(title);
  if (source !== undefined) updates.push('source = ?'), params.push(source);
  if (industry !== undefined) updates.push('industry = ?'), params.push(industry);
  if (summary !== undefined) updates.push('summary = ?'), params.push(summary);
  if (content !== undefined) updates.push('content = ?'), params.push(content);
  if (url !== undefined) updates.push('url = ?'), params.push(url);
  if (publishedAt !== undefined) updates.push('published_at = ?'), params.push(publishedAt);
  params.push(req.params.id);

  if (updates.length === 0) {
    return res.status(400).json({ message: '没有提供更新数据' });
  }

  db.prepare(`UPDATE industry_news SET ${updates.join(', ')} WHERE id = ?`).run(...params);
  res.json({ message: '新闻更新成功' });
});

router.delete('/:id', auth, authorize('admin'), (req, res) => {
  db.prepare('DELETE FROM industry_news WHERE id = ?').run(req.params.id);
  res.json({ message: '新闻删除成功' });
});

module.exports = router;
