const express = require('express');
const db = require('../db/init');
const { authMiddleware } = require('../middleware/auth');
const { fetchLotteryResult, updateTicketsStatus, getEstimatedDrawTime } = require('../services/lottery');

const router = express.Router();

router.use(authMiddleware);

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

  if (!game || !issue) {
    return res.status(400).json({ error: '请提供彩票类型和期号' });
  }

  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) {
    res.status(500).json({ error: '查询失败' });
  }
});

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

// 获取最近开奖记录
router.get('/recent', async (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));

  const results = db.prepare(query).all(...params);
  res.json(results.map(r => ({ ...r, numbers: JSON.parse(r.numbers) })));
});

module.exports = router;
