const express = require('express');
const db = require('../config/database');
const { auth } = require('../middleware/auth');

const router = express.Router();

router.get('/', auth, (req, res) => {
  const { page = 1, limit = 20, unreadOnly } = req.query;
  const offset = (page - 1) * limit;
  
  let query = 'SELECT * FROM notifications WHERE user_id = ?';
  const params = [req.user.id];
  
  if (unreadOnly === 'true') {
    query += ' AND is_read = 0';
  }
  
  query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  params.push(parseInt(limit), offset);
  
  const notifications = db.prepare(query).all(...params);
  const total = db.prepare('SELECT COUNT(*) as total FROM notifications WHERE user_id = ?').get(req.user.id);
  const unread = db.prepare('SELECT COUNT(*) as unread FROM notifications WHERE user_id = ? AND is_read = 0').get(req.user.id);
  
  res.json({
    notifications,
    pagination: {
      page: parseInt(page),
      limit: parseInt(limit),
      total: total?.total || 0,
      unread: unread?.unread || 0
    }
  });
});

router.put('/:id/read', auth, (req, res) => {
  db.prepare('UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ?').run(req.params.id, req.user.id);
  res.json({ message: '通知已标记为已读' });
});

router.put('/read-all', auth, (req, res) => {
  db.prepare('UPDATE notifications SET is_read = 1 WHERE user_id = ?').run(req.user.id);
  res.json({ message: '所有通知已标记为已读' });
});

router.delete('/:id', auth, (req, res) => {
  db.prepare('DELETE FROM notifications WHERE id = ? AND user_id = ?').run(req.params.id, req.user.id);
  res.json({ message: '通知已删除' });
});

module.exports = router;
