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

const router = express.Router();

router.get('/', auth, (req, res) => {
  const { page = 1, limit = 20, status } = req.query;
  const offset = (page - 1) * limit;

  let query = `
    SELECT lp.*, k.title as knowledge_title, k.category as knowledge_category
    FROM learning_progress lp
    JOIN knowledge k ON lp.knowledge_id = k.id
    WHERE lp.user_id = ?
  `;
  const params = [req.user.id];

  if (status) {
    query += ' AND lp.status = ?';
    params.push(status);
  }

  query += ' ORDER BY lp.updated_at DESC LIMIT ? OFFSET ?';
  params.push(parseInt(limit), offset);

  const progress = 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({
    learning_progress: progress,
    pagination: {
      page: parseInt(page),
      limit: parseInt(limit),
      total: countResult?.total || 0
    }
  });
});

router.get('/stats', auth, (req, res) => {
  const stats = db.prepare(`
    SELECT
      COUNT(*) as total,
      SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
      SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
      SUM(CASE WHEN status = 'not_started' THEN 1 ELSE 0 END) as not_started,
      AVG(CASE WHEN status = 'completed' THEN progress ELSE NULL END) as avg_progress
    FROM learning_progress
    WHERE user_id = ?
  `).get(req.user.id);

  res.json({ stats });
});

router.post('/:knowledgeId', auth, (req, res) => {
  const knowledgeId = parseInt(req.params.knowledgeId);
  const { progress, status, notes } = req.body;

  const knowledge = db.prepare('SELECT * FROM knowledge WHERE id = ?').get(knowledgeId);
  if (!knowledge) {
    return res.status(404).json({ message: '知识不存在' });
  }

  try {
    const existing = db.prepare('SELECT * FROM learning_progress WHERE user_id = ? AND knowledge_id = ?').get(req.user.id, knowledgeId);

    if (existing) {
      const updates = [];
      const params = [];

      if (progress !== undefined) { updates.push('progress = ?'); params.push(progress); }
      if (status !== undefined) { updates.push('status = ?'); params.push(status); }
      if (notes !== undefined) { updates.push('notes = ?'); params.push(notes); }
      if (status === 'completed') { updates.push('completed_at = CURRENT_TIMESTAMP'); }
      updates.push('updated_at = CURRENT_TIMESTAMP');
      params.push(req.user.id, knowledgeId);

      db.prepare(`UPDATE learning_progress SET ${updates.join(', ')} WHERE user_id = ? AND knowledge_id = ?`).run(...params);
      res.json({ message: '学习进度更新成功' });
    } else {
      const result = db.prepare(
        `INSERT INTO learning_progress (user_id, knowledge_id, progress, status, notes)
         VALUES (?, ?, ?, ?, ?)`
      ).run(
        req.user.id, knowledgeId, progress || 0, status || 'in_progress', notes || ''
      );

      res.status(201).json({ message: '学习进度创建成功', learning_progress_id: result.lastInsertRowid });
    }
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

router.delete('/:knowledgeId', auth, (req, res) => {
  const knowledgeId = parseInt(req.params.knowledgeId);

  db.prepare('DELETE FROM learning_progress WHERE user_id = ? AND knowledge_id = ?').run(req.user.id, knowledgeId);
  res.json({ message: '学习进度已删除' });
});

module.exports = router;
