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

const router = express.Router();

router.get('/', auth, authorize('admin'), (req, res) => {
  const { page = 1, limit = 20, role, search } = req.query;
  const offset = (page - 1) * limit;
  
  let query = 'SELECT id, username, email, full_name, phone, role, department, is_active, created_at, updated_at FROM users WHERE 1=1';
  const params = [];
  
  if (role) {
    query += ' AND role = ?';
    params.push(role);
  }
  
  if (search) {
    query += ' AND (username LIKE ? OR full_name LIKE ? OR email LIKE ?)';
    const searchTerm = `%${search}%`;
    params.push(searchTerm, searchTerm, searchTerm);
  }
  
  query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  params.push(parseInt(limit), offset);
  
  const users = db.prepare(query).all(...params);
  
  let countQuery = query.replace(/SELECT.*FROM/, 'SELECT COUNT(*) as total FROM').replace(/ORDER BY.*$/, '');
  countQuery = countQuery.replace(/ LIMIT \? OFFSET \?$/, '');
  const countParams = params.slice(0, -2);
  const countResult = db.prepare(countQuery).get(...countParams);
  
  res.json({
    users,
    pagination: {
      page: parseInt(page),
      limit: parseInt(limit),
      total: countResult?.total || 0
    }
  });
});

router.get('/:id', auth, (req, res) => {
  if (req.user.role !== 'admin' && req.user.id !== parseInt(req.params.id)) {
    return res.status(403).json({ message: '权限不足' });
  }
  
  const user = db.prepare(
    'SELECT id, username, email, full_name, phone, role, department, is_active, created_at, updated_at FROM users WHERE id = ?'
  ).get(req.params.id);
  
  if (!user) {
    return res.status(404).json({ message: '用户不存在' });
  }
  res.json({ user });
});

router.post('/', auth, authorize('admin'), [
  body('username').isLength({ min: 3 }).withMessage('用户名至少3个字符'),
  body('password').isLength({ min: 6 }).withMessage('密码至少6个字符'),
  body('email').isEmail().withMessage('请输入有效的邮箱地址'),
  body('fullName').notEmpty().withMessage('姓名不能为空'),
  body('role').isIn(['admin', 'investment_manager', 'analyst', 'user']).withMessage('无效的角色')
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.error('用户创建验证失败:', errors.array());
    // 返回第一个验证错误的消息
    const firstError = errors.array()[0];
    return res.status(400).json({ message: firstError?.msg || '验证失败' });
  }

  const { username, password, email, fullName, phone, role, department } = req.body;

  const existingUser = db.prepare('SELECT id FROM users WHERE username = ? OR email = ?').get(username, email);
  if (existingUser) {
    return res.status(400).json({ message: '用户名或邮箱已存在' });
  }

  try {
    const hashedPassword = bcrypt.hashSync(password, 10);
    const result = db.prepare(
      'INSERT INTO users (username, password, email, full_name, phone, role, department) VALUES (?, ?, ?, ?, ?, ?, ?)'
    ).run(username, hashedPassword, email, fullName, phone || '', role, department || '');

    res.status(201).json({
      message: '用户创建成功',
      user: {
        id: result.lastInsertRowid,
        username,
        email,
        fullName,
        role,
        department
      }
    });
  } catch (error) {
    console.error('用户创建失败:', error);
    res.status(500).json({ message: '服务器错误: ' + error.message });
  }
});

router.put('/:id', auth, [
  body('fullName').optional().notEmpty().withMessage('姓名不能为空'),
  body('email').optional().isEmail().withMessage('请输入有效的邮箱地址'),
  body('role').optional().isIn(['admin', 'investment_manager', 'analyst', 'user']).withMessage('无效的角色')
], (req, res) => {
  const targetId = parseInt(req.params.id);
  
  if (req.user.role !== 'admin' && req.user.id !== targetId) {
    return res.status(403).json({ message: '权限不足' });
  }

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  const { fullName, email, phone, role, department, isActive } = req.body;

  const user = db.prepare('SELECT * FROM users WHERE id = ?').get(targetId);
  if (!user) {
    return res.status(404).json({ message: '用户不存在' });
  }

  if (email && email !== user.email) {
    const existingUser = db.prepare('SELECT id FROM users WHERE email = ? AND id != ?').get(email, targetId);
    if (existingUser) {
      return res.status(400).json({ message: '邮箱已存在' });
    }
  }

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

  if (fullName !== undefined) { updates.push('full_name = ?'); params.push(fullName); }
  if (email !== undefined) { updates.push('email = ?'); params.push(email); }
  if (phone !== undefined) { updates.push('phone = ?'); params.push(phone); }
  if (req.user.role === 'admin') {
    if (role !== undefined) { updates.push('role = ?'); params.push(role); }
    if (department !== undefined) { updates.push('department = ?'); params.push(department); }
    if (isActive !== undefined) { updates.push('is_active = ?'); params.push(isActive ? 1 : 0); }
  }

  if (updates.length === 0) {
    return res.status(400).json({ message: '没有提供更新数据' });
  }

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

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

router.delete('/:id', auth, authorize('admin'), (req, res) => {
  const targetId = parseInt(req.params.id);
  
  if (targetId === req.user.id) {
    return res.status(400).json({ message: '不能删除自己的账户' });
  }

  const user = db.prepare('SELECT id FROM users WHERE id = ?').get(targetId);
  if (!user) {
    return res.status(404).json({ message: '用户不存在' });
  }

  db.prepare('DELETE FROM users WHERE id = ?').run(targetId);
  res.json({ message: '用户删除成功' });
});

module.exports = router;
