const jwt = require('jsonwebtoken');
const User = require('../models/User');
const Role = require('../models/Role');
const responseFormat = require('../utils/response');

// JWT认证中间件
const jwtAuth = async (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    console.log('Authorization header:', authHeader);
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json(responseFormat.error('未提供有效的认证token'));
    }

    const token = authHeader.substring(7);
    console.log('提取的token:', token);
    console.log('token类型:', typeof token);
    console.log('token长度:', token.length);

    // 首先尝试固定token验证
    const user = await User.findOne({
      where: { 
        fixed_token: token,
        status: 'active'
      },
      include: [{
        model: Role,
        as: 'role',
        attributes: ['id', 'name', 'permissions']
      }]
    });

    if (user) {
      // 固定token验证成功
      req.user = {
        id: user.id,
        userId: user.id,
        username: user.username,
        role_id: user.role_id,
        role: user.role,
        permissions: user.role ? user.role.permissions : [],
        type: 'fixed_token'
      };
      return next();
    }

    // 如果固定token验证失败，尝试JWT验证
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      
      if (decoded.type !== 'access') {
        return res.status(401).json(responseFormat.error('Token类型错误'));
      }

      // 验证用户是否存在且状态正常
      const jwtUser = await User.findOne({
        where: { 
          id: decoded.id,
          status: 'active'
        },
        include: [{
          model: Role,
          as: 'role',
          attributes: ['id', 'name', 'permissions']
        }]
      });

      if (!jwtUser) {
        return res.status(401).json(responseFormat.error('用户不存在或已被禁用'));
      }

      req.user = {
        id: decoded.id,
        userId: decoded.id,
        username: decoded.username,
        role_id: decoded.role_id,
        role: jwtUser.role,
        permissions: decoded.permissions || (jwtUser.role ? jwtUser.role.permissions : []),
        type: 'jwt'
      };
      
      return next();
    } catch (jwtError) {
      if (jwtError.name === 'TokenExpiredError') {
        return res.status(401).json(responseFormat.error('Token已过期', 'TOKEN_EXPIRED'));
      } else if (jwtError.name === 'JsonWebTokenError') {
        return res.status(401).json(responseFormat.error('Token无效'));
      }
      throw jwtError;
    }
  } catch (error) {
    console.error('Token验证错误:', error);
    return res.status(500).json(responseFormat.error('服务器内部错误'));
  }
};

// 权限检查中间件
const checkPermission = (resource, action) => {
  return async (req, res, next) => {
    try {
      console.log(`权限检查 - 资源: ${resource}, 操作: ${action}, 用户:`, req.user);
      const user = req.user;
      
      if (!user || !user.role_id) {
        console.log('权限检查失败 - 用户角色信息缺失');
        return res.status(403).json(responseFormat.error('用户角色信息缺失'));
      }
      
      let permissions = [];
      
      // 优先使用JWT中的权限信息
      if (user.permissions) {
        if (typeof user.permissions === 'string') {
          try {
            permissions = JSON.parse(user.permissions);
          } catch (e) {
            console.log('JWT权限解析失败:', e.message);
            permissions = [];
          }
        } else if (Array.isArray(user.permissions)) {
          permissions = user.permissions;
        }
      }
      
      const requiredPermission = `${resource}:${action}`;
      
      // 首先检查JWT中的权限
      let hasPermission = permissions.includes(requiredPermission) || 
                         permissions.includes('*:*') || 
                         permissions.includes('*');
      
      // 如果JWT中没有权限信息，或者JWT权限不足，从数据库查询最新权限
      if (permissions.length === 0 || !hasPermission) {
        console.log('JWT权限不足或为空，从数据库获取最新权限...');
        const { Role, RolePermission, Permission } = require('../models');
        const userRole = await Role.findByPk(user.role_id);
        
        if (!userRole) {
          console.log('权限检查失败 - 用户角色不存在, role_id:', user.role_id);
          return res.status(403).json(responseFormat.error('用户角色不存在'));
        }
        
        // 从RolePermission表获取权限
        const rolePermissions = await RolePermission.findAll({
          where: { 
            role_id: user.role_id,
            granted: true 
          },
          include: [{
            model: Permission,
            as: 'permission',
            attributes: ['code']
          }]
        });
        
        permissions = rolePermissions.map(rp => rp.permission.code);
        console.log('从RolePermission表获取的最新权限:', permissions);
        
        // 重新检查权限
        hasPermission = permissions.includes(requiredPermission) || 
                       permissions.includes('*:*') || 
                       permissions.includes('*');
      }
      
      console.log('权限检查 - 用户权限:', permissions, '需要权限:', requiredPermission, '是否有权限:', hasPermission);
      
      // 检查权限或超级管理员权限
      if (!hasPermission) {
        console.log('权限检查失败 - 权限不足');
        return res.status(403).json(responseFormat.error('权限不足'));
      }
      
      console.log('权限检查通过');
      next();
    } catch (error) {
      return res.status(500).json(responseFormat.error('权限验证失败'));
    }
  };
};

// 可选认证中间件（不强制要求认证）
const optionalAuth = (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');
  
  if (token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      req.user = decoded;
    } catch (error) {
      // 令牌无效，但不阻止请求
      console.warn('可选认证令牌无效:', error.message);
    }
  }
  
  next();
};

// 别名导出以匹配路由中的使用
const authenticateToken = jwtAuth;
const requirePermission = (permission) => {
  const [resource, action] = permission.split(':');
  return checkPermission(resource, action);
};

module.exports = { 
  jwtAuth, 
  checkPermission, 
  optionalAuth,
  authenticateToken,
  requirePermission
};