const express = require('express');
const db = require('../db/init');
const { authMiddleware } = require('../middleware/auth');
const { fetchLotteryResult, updateTicketsStatus, getEstimatedDrawTime } = require('../services/lottery');
const { refreshLimiter, standardLimiter } = require('../middleware/rateLimiter');
const { validate, lotteryQueryRules } = require('../middleware/validate');
const logger = require('../services/logger');

const router = express.Router();

router.use(authMiddleware);

// 查询开奖结果
router.get('/result', lotteryQueryRules, validate, async (req, res) => {
  const { game, issue } = req.query;

  try {
    const result = await fetchLotteryResult(game, issue);
    if (result) {
      res.json(result);
    } else {
      const estimatedTime = getEstimatedDrawTime(game, issue);
      res.json({
        message: '暂未开奖或未找到数据',
        drawn: false,
        estimated_draw_time: estimatedTime
      });
    }
  } catch (err) {
    logger.error('查询开奖结果失败', { game, issue, error: err.message });
    res.status(500).json({ error: '查询失败' });
  }
});

// 刷新用户所有待开奖彩票状态
router.post('/refresh', refreshLimiter, async (req, res) => {
  try {
    await updateTicketsStatus(req.user.id);
    logger.info(`刷新开奖: userId=${req.user.id}`);
    res.json({ message: '刷新成功' });
  } catch (err) {
    logger.error('刷新开奖失败', { error: err.message });
    res.status(500).json({ error: '刷新失败' });
  }
});

// 获取最近开奖记录
router.get('/recent', standardLimiter, (req, res) => {
  const { game, limit = 10 } = req.query;

  let query = 'SELECT * FROM lottery_results';
  const params = [];

  if (game) {
    query += ' WHERE game = ?';
    params.push(game);
  }

  query += ' ORDER BY draw_date DESC LIMIT ?';
  params.push(Number(limit));

  try {
    const results = db.prepare(query).all(...params);
    res.json(results.map(r => ({ ...r, numbers: JSON.parse(r.numbers) })));
  } catch (err) {
    logger.error('获取最近开奖记录失败', { error: err.message });
    res.status(500).json({ error: '查询失败' });
  }
});

module.exports = router;
