const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const router = express.Router();

// 中间件将在服务器启动时设置
let pool = null;

// 设置数据库连接（从主服务器导入）
function setMiddleware(dbPool) {
  pool = dbPool;
  console.log('✅ Auth模块数据库连接设置完成');
}

// JWT密钥（生产环境应从环境变量获取）
const JWT_SECRET = process.env.JWT_SECRET || 'xlxumu_jwt_secret_key_2024';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const {
      username,
      phone,
      email,
      password,
      real_name,
      user_type = 'farmer',
      verification_code
    } = req.body;

    // 验证必填字段
    if (!username || !phone || !password) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段：username, phone, password',
        code: 'MISSING_REQUIRED_FIELDS'
      });
    }

    // 验证密码强度
    if (password.length < 6) {
      return res.status(400).json({
        success: false,
        message: '密码长度至少6位',
        code: 'WEAK_PASSWORD'
      });
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      return res.status(400).json({
        success: false,
        message: '手机号格式不正确',
        code: 'INVALID_PHONE'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      const mockToken = jwt.sign(
        { userId: Math.floor(Math.random() * 1000) + 100, username, user_type },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );

      return res.status(201).json({
        success: true,
        message: '注册成功（模拟）',
        data: {
          user: {
            id: Math.floor(Math.random() * 1000) + 100,
            username,
            phone,
            email,
            real_name,
            user_type,
            status: 1
          },
          token: mockToken,
          expires_in: JWT_EXPIRES_IN
        }
      });
    }

    // 检查用户名和手机号是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT id, username, phone FROM users WHERE (username = ? OR phone = ?) AND deleted_at IS NULL',
      [username, phone]
    );

    if (existingUsers.length > 0) {
      const existing = existingUsers[0];
      const conflictField = existing.username === username ? '用户名' : '手机号';
      return res.status(400).json({
        success: false,
        message: `${conflictField}已存在`,
        code: 'USER_EXISTS'
      });
    }

    // 生成密码哈希
    const salt = await bcrypt.genSalt(10);
    const passwordHash = await bcrypt.hash(password, salt);

    // 插入新用户
    const insertQuery = `
      INSERT INTO users (
        username, phone, email, password_hash, salt, real_name, user_type, status
      ) VALUES (?, ?, ?, ?, ?, ?, ?, 1)
    `;

    const [result] = await pool.execute(insertQuery, [
      username, phone, email, passwordHash, salt, real_name, user_type
    ]);

    // 生成JWT令牌
    const token = jwt.sign(
      { 
        userId: result.insertId, 
        username, 
        user_type,
        phone 
      },
      JWT_SECRET,
      { expiresIn: JWT_EXPIRES_IN }
    );

    // 获取新创建的用户信息
    const [newUser] = await pool.execute(
      `SELECT 
        id, username, phone, email, real_name, user_type, status, created_at
      FROM users WHERE id = ?`,
      [result.insertId]
    );

    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        user: newUser[0],
        token,
        expires_in: JWT_EXPIRES_IN
      }
    });
  } catch (error) {
    console.error('用户注册失败:', error);
    res.status(500).json({
      success: false,
      message: '注册失败',
      code: 'REGISTER_ERROR'
    });
  }
});

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { username, password, login_type = 'username' } = req.body;

    // 验证必填字段
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空',
        code: 'MISSING_CREDENTIALS'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      const mockToken = jwt.sign(
        { userId: 1, username, user_type: 'farmer' },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );

      return res.json({
        success: true,
        message: '登录成功（模拟）',
        data: {
          user: {
            id: 1,
            username,
            phone: '13800138001',
            real_name: '张三',
            user_type: 'farmer',
            status: 1
          },
          token: mockToken,
          expires_in: JWT_EXPIRES_IN
        }
      });
    }

    // 根据登录类型构建查询条件
    let whereClause = 'username = ?';
    if (login_type === 'phone') {
      whereClause = 'phone = ?';
    } else if (login_type === 'email') {
      whereClause = 'email = ?';
    }

    // 查询用户
    const [users] = await pool.execute(
      `SELECT 
        id, username, phone, email, real_name, user_type, status, 
        password_hash, last_login_at
      FROM users 
      WHERE ${whereClause} AND deleted_at IS NULL`,
      [username]
    );

    if (users.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误',
        code: 'INVALID_CREDENTIALS'
      });
    }

    const user = users[0];

    // 检查用户状态
    if (user.status !== 1) {
      return res.status(401).json({
        success: false,
        message: '账户已被禁用',
        code: 'ACCOUNT_DISABLED'
      });
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password_hash);
    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误',
        code: 'INVALID_CREDENTIALS'
      });
    }

    // 更新最后登录时间
    await pool.execute(
      'UPDATE users SET last_login_at = CURRENT_TIMESTAMP WHERE id = ?',
      [user.id]
    );

    // 生成JWT令牌
    const token = jwt.sign(
      { 
        userId: user.id, 
        username: user.username, 
        user_type: user.user_type,
        phone: user.phone 
      },
      JWT_SECRET,
      { expiresIn: JWT_EXPIRES_IN }
    );

    // 移除敏感信息
    delete user.password_hash;

    res.json({
      success: true,
      message: '登录成功',
      data: {
        user,
        token,
        expires_in: JWT_EXPIRES_IN
      }
    });
  } catch (error) {
    console.error('用户登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败',
      code: 'LOGIN_ERROR'
    });
  }
});

// 获取当前用户信息
router.get('/profile', async (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供访问令牌',
        code: 'NO_TOKEN'
      });
    }

    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      
      if (!pool) {
        // 数据库不可用时返回模拟数据
        return res.json({
          success: true,
          data: {
            id: decoded.userId,
            username: decoded.username,
            phone: decoded.phone,
            real_name: '张三',
            user_type: decoded.user_type,
            status: 1,
            created_at: '2024-01-01 00:00:00'
          }
        });
      }

      // 查询用户信息
      const [users] = await pool.execute(
        `SELECT 
          id, username, phone, email, real_name, id_card, gender, birthday, 
          address, user_type, status, avatar, last_login_at, created_at, updated_at
        FROM users 
        WHERE id = ? AND deleted_at IS NULL`,
        [decoded.userId]
      );

      if (users.length === 0) {
        return res.status(401).json({
          success: false,
          message: '用户不存在',
          code: 'USER_NOT_FOUND'
        });
      }

      res.json({
        success: true,
        data: users[0]
      });
    } catch (jwtError) {
      return res.status(401).json({
        success: false,
        message: '访问令牌无效',
        code: 'INVALID_TOKEN'
      });
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户信息失败',
      code: 'GET_PROFILE_ERROR'
    });
  }
});

// 更新用户资料
router.put('/profile', async (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供访问令牌',
        code: 'NO_TOKEN'
      });
    }

    const {
      real_name,
      email,
      gender,
      birthday,
      address,
      avatar
    } = req.body;

    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      
      if (!pool) {
        // 数据库不可用时返回模拟响应
        return res.json({
          success: true,
          message: '资料更新成功（模拟）',
          data: {
            id: decoded.userId,
            real_name,
            email,
            gender,
            birthday,
            address,
            avatar,
            updated_at: new Date().toISOString()
          }
        });
      }

      // 更新用户资料
      const updateQuery = `
        UPDATE users 
        SET real_name = ?, email = ?, gender = ?, birthday = ?, 
            address = ?, avatar = ?, updated_at = CURRENT_TIMESTAMP
        WHERE id = ? AND deleted_at IS NULL
      `;

      await pool.execute(updateQuery, [
        real_name, email, gender, birthday, address, avatar, decoded.userId
      ]);

      // 获取更新后的用户信息
      const [updatedUser] = await pool.execute(
        `SELECT 
          id, username, phone, email, real_name, gender, birthday, 
          address, avatar, user_type, status, updated_at
        FROM users WHERE id = ?`,
        [decoded.userId]
      );

      res.json({
        success: true,
        message: '资料更新成功',
        data: updatedUser[0]
      });
    } catch (jwtError) {
      return res.status(401).json({
        success: false,
        message: '访问令牌无效',
        code: 'INVALID_TOKEN'
      });
    }
  } catch (error) {
    console.error('更新用户资料失败:', error);
    res.status(500).json({
      success: false,
      message: '更新资料失败',
      code: 'UPDATE_PROFILE_ERROR'
    });
  }
});

// 修改密码
router.post('/change-password', async (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供访问令牌',
        code: 'NO_TOKEN'
      });
    }

    const { old_password, new_password } = req.body;

    // 验证必填字段
    if (!old_password || !new_password) {
      return res.status(400).json({
        success: false,
        message: '旧密码和新密码不能为空',
        code: 'MISSING_PASSWORDS'
      });
    }

    // 验证新密码强度
    if (new_password.length < 6) {
      return res.status(400).json({
        success: false,
        message: '新密码长度至少6位',
        code: 'WEAK_PASSWORD'
      });
    }

    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      
      if (!pool) {
        // 数据库不可用时返回模拟响应
        return res.json({
          success: true,
          message: '密码修改成功（模拟）'
        });
      }

      // 查询用户当前密码
      const [users] = await pool.execute(
        'SELECT id, password_hash FROM users WHERE id = ? AND deleted_at IS NULL',
        [decoded.userId]
      );

      if (users.length === 0) {
        return res.status(401).json({
          success: false,
          message: '用户不存在',
          code: 'USER_NOT_FOUND'
        });
      }

      const user = users[0];

      // 验证旧密码
      const isOldPasswordValid = await bcrypt.compare(old_password, user.password_hash);
      if (!isOldPasswordValid) {
        return res.status(400).json({
          success: false,
          message: '旧密码不正确',
          code: 'INVALID_OLD_PASSWORD'
        });
      }

      // 生成新密码哈希
      const salt = await bcrypt.genSalt(10);
      const newPasswordHash = await bcrypt.hash(new_password, salt);

      // 更新密码
      await pool.execute(
        'UPDATE users SET password_hash = ?, salt = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
        [newPasswordHash, salt, decoded.userId]
      );

      res.json({
        success: true,
        message: '密码修改成功'
      });
    } catch (jwtError) {
      return res.status(401).json({
        success: false,
        message: '访问令牌无效',
        code: 'INVALID_TOKEN'
      });
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    res.status(500).json({
      success: false,
      message: '修改密码失败',
      code: 'CHANGE_PASSWORD_ERROR'
    });
  }
});

// 发送验证码（手机验证码）
router.post('/send-verification-code', async (req, res) => {
  try {
    const { phone, type = 'register' } = req.body;

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      return res.status(400).json({
        success: false,
        message: '手机号格式不正确',
        code: 'INVALID_PHONE'
      });
    }

    // 生成6位验证码
    const verificationCode = Math.floor(100000 + Math.random() * 900000).toString();

    // TODO: 集成短信服务发送验证码
    // 这里暂时只是模拟发送
    console.log(`发送验证码到 ${phone}: ${verificationCode}`);

    // 在实际项目中，应该将验证码存储到Redis或数据库中，设置过期时间
    // 这里返回模拟响应
    res.json({
      success: true,
      message: '验证码发送成功',
      data: {
        phone,
        expires_in: 300, // 5分钟过期
        // 开发环境下返回验证码，生产环境不应返回
        verification_code: process.env.NODE_ENV === 'development' ? verificationCode : undefined
      }
    });
  } catch (error) {
    console.error('发送验证码失败:', error);
    res.status(500).json({
      success: false,
      message: '发送验证码失败',
      code: 'SEND_CODE_ERROR'
    });
  }
});

// 重置密码
router.post('/reset-password', async (req, res) => {
  try {
    const { phone, verification_code, new_password } = req.body;

    // 验证必填字段
    if (!phone || !verification_code || !new_password) {
      return res.status(400).json({
        success: false,
        message: '手机号、验证码和新密码不能为空',
        code: 'MISSING_REQUIRED_FIELDS'
      });
    }

    // 验证新密码强度
    if (new_password.length < 6) {
      return res.status(400).json({
        success: false,
        message: '新密码长度至少6位',
        code: 'WEAK_PASSWORD'
      });
    }

    // TODO: 验证验证码是否正确和未过期
    // 这里暂时跳过验证码验证

    if (!pool) {
      // 数据库不可用时返回模拟响应
      return res.json({
        success: true,
        message: '密码重置成功（模拟）'
      });
    }

    // 查询用户
    const [users] = await pool.execute(
      'SELECT id FROM users WHERE phone = ? AND deleted_at IS NULL',
      [phone]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '手机号未注册',
        code: 'PHONE_NOT_REGISTERED'
      });
    }

    const user = users[0];

    // 生成新密码哈希
    const salt = await bcrypt.genSalt(10);
    const passwordHash = await bcrypt.hash(new_password, salt);

    // 更新密码
    await pool.execute(
      'UPDATE users SET password_hash = ?, salt = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [passwordHash, salt, user.id]
    );

    res.json({
      success: true,
      message: '密码重置成功'
    });
  } catch (error) {
    console.error('重置密码失败:', error);
    res.status(500).json({
      success: false,
      message: '重置密码失败',
      code: 'RESET_PASSWORD_ERROR'
    });
  }
});

// 用户登出
router.post('/logout', async (req, res) => {
  try {
    // JWT是无状态的，客户端删除token即可实现登出
    // 如果需要服务端控制，可以维护一个黑名单
    res.json({
      success: true,
      message: '登出成功'
    });
  } catch (error) {
    console.error('用户登出失败:', error);
    res.status(500).json({
      success: false,
      message: '登出失败',
      code: 'LOGOUT_ERROR'
    });
  }
});

// 验证令牌
router.post('/verify-token', async (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '') || req.body.token;
    
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供访问令牌',
        code: 'NO_TOKEN'
      });
    }

    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      
      res.json({
        success: true,
        message: '令牌有效',
        data: {
          userId: decoded.userId,
          username: decoded.username,
          user_type: decoded.user_type,
          expires_at: new Date(decoded.exp * 1000).toISOString()
        }
      });
    } catch (jwtError) {
      return res.status(401).json({
        success: false,
        message: '访问令牌无效或已过期',
        code: 'INVALID_TOKEN'
      });
    }
  } catch (error) {
    console.error('验证令牌失败:', error);
    res.status(500).json({
      success: false,
      message: '验证令牌失败',
      code: 'VERIFY_TOKEN_ERROR'
    });
  }
});

module.exports = {
  router,
  setMiddleware
};