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

const router = express.Router();

const uploadDir = path.join(__dirname, '../../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 50 * 1024 * 1024
  }
});

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

  let query = `
    SELECT k.*, u.full_name as created_by_name
    FROM knowledge k
    LEFT JOIN users u ON k.created_by = u.id
    WHERE 1=1
  `;
  const params = [];

  if (category) {
    query += ' AND k.category = ?';
    params.push(category);
  }

  if (isPublic !== undefined) {
    query += ' AND (k.is_public = ? OR k.created_by = ?)';
    params.push(isPublic === 'true' ? 1 : 0, req.user.id);
  } else {
    query += ' AND (k.is_public = 1 OR k.created_by = ?)';
    params.push(req.user.id);
  }

  if (search) {
    query += ' AND (k.title LIKE ? OR k.content LIKE ?)';
    const searchTerm = `%${search}%`;
    params.push(searchTerm, searchTerm);
  }

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

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

router.get('/categories', auth, (req, res) => {
  const categories = db.prepare('SELECT DISTINCT category FROM knowledge WHERE category IS NOT NULL AND category != ""').all();
  res.json({ categories: categories.map(c => c.category) });
});

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

  const knowledge = db.prepare(`
    SELECT k.*, u.full_name as created_by_name
    FROM knowledge k
    LEFT JOIN users u ON k.created_by = u.id
    WHERE k.id = ?
  `).get(knowledgeId);

  if (!knowledge) {
    return res.status(404).json({ message: '知识不存在' });
  }

  if (!knowledge.is_public && knowledge.created_by !== req.user.id) {
    return res.status(403).json({ message: '无权访问此知识' });
  }

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

  res.json({ knowledge, learning_progress: learningProgress || null });
});

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

  const { title, category, content, tags, isPublic } = req.body;

  try {
    const result = db.prepare(
      `INSERT INTO knowledge (title, category, content, tags, file_path, file_name, created_by, is_public)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
    ).run(
      title, category || '', content || '', tags ? JSON.stringify(tags) : null,
      req.file ? req.file.filename : null, req.file ? req.file.originalname : null,
      req.user.id, isPublic === 'true' ? 1 : 0
    );

    res.status(201).json({ message: '知识创建成功', knowledge_id: result.lastInsertRowid });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

router.put('/:id', auth, upload.single('file'), (req, res) => {
  const knowledgeId = parseInt(req.params.id);

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

  if (knowledge.created_by !== req.user.id && req.user.role !== 'admin') {
    return res.status(403).json({ message: '无权编辑此知识' });
  }

  const { title, category, content, tags, isPublic } = req.body;

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

  if (title !== undefined) { updates.push('title = ?'); params.push(title); }
  if (category !== undefined) { updates.push('category = ?'); params.push(category); }
  if (content !== undefined) { updates.push('content = ?'); params.push(content); }
  if (tags !== undefined) { updates.push('tags = ?'); params.push(JSON.stringify(tags)); }
  if (isPublic !== undefined) { updates.push('is_public = ?'); params.push(isPublic === 'true' ? 1 : 0); }
  if (req.file) {
    if (knowledge.file_path) {
      const oldPath = path.join(uploadDir, knowledge.file_path);
      if (fs.existsSync(oldPath)) {
        fs.unlinkSync(oldPath);
      }
    }
    updates.push('file_path = ?');
    params.push(req.file.filename);
    updates.push('file_name = ?');
    params.push(req.file.originalname);
  }

  updates.push('updated_at = CURRENT_TIMESTAMP');
  params.push(knowledgeId);

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

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

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

  if (knowledge.created_by !== req.user.id && req.user.role !== 'admin') {
    return res.status(403).json({ message: '无权删除此知识' });
  }

  try {
    if (knowledge.file_path) {
      const filePath = path.join(uploadDir, knowledge.file_path);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }

    db.prepare('DELETE FROM knowledge WHERE id = ?').run(knowledgeId);
    res.json({ message: '知识删除成功' });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

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

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

  if (!knowledge.file_path) {
    return res.status(404).json({ message: '文件不存在' });
  }

  const filePath = path.join(uploadDir, knowledge.file_path);
  if (!fs.existsSync(filePath)) {
    return res.status(404).json({ message: '文件不存在' });
  }

  res.download(filePath, knowledge.file_name);
});

module.exports = router;
