/**
 * 认证中间件（清晰重构版）
 * 由 省胜优铺 项目组从反混淆版重写，功能与原版等价
 * authUser / authAdmin / optionalAuth / requirePermission
 */
const jwt = require('jsonwebtoken');
const config = require('../../config');
const { get } = require('../utils/db');

/**
 * 解析 Bearer token，返回 payload 或 null
 */
function extractToken(req) {
  const auth = req.headers && req.headers.authorization;
  if (!auth || typeof auth !== 'string') return null;
  const m = auth.match(/^Bearer\s+(.+)$/i);
  return m ? m[1].trim() : null;
}

/**
 * 普通用户鉴权：需登录
 * 设置 req.user / req.userId
 */
function authUser(req, res, next) {
  const token = extractToken(req);
  if (!token) {
    return res.status(401).json({ code: 401, message: '请先登录' });
  }
  try {
    const payload = jwt.verify(token, config.jwtSecret);
    const user = get(
      'SELECT id, nickname, avatar, phone, level_id, experience, balance FROM users WHERE id = ?',
      [payload.userId]
    );
    if (!user) {
      return res.status(401).json({ code: 401, message: '用户不存在' });
    }
    req.user = user;
    req.userId = user.id;
    next();
  } catch (e) {
    return res.status(401).json({ code: 401, message: '登录已过期，请重新登录' });
  }
}

/**
 * 管理员鉴权：需登录且为管理员
 */
function authAdmin(req, res, next) {
  const token = extractToken(req);
  if (!token) {
    return res.status(401).json({ code: 401, message: '请先登录' });
  }
  try {
    const payload = jwt.verify(token, config.jwtSecret);
    const user = get(
      'SELECT id, nickname, phone, level_id, is_admin FROM users WHERE id = ?',
      [payload.userId]
    );
    if (!user) {
      return res.status(401).json({ code: 401, message: '用户不存在' });
    }
    if (!user.is_admin) {
      return res.status(403).json({ code: 403, message: '无管理员权限' });
    }
    req.user = user;
    req.userId = user.id;
    next();
  } catch (e) {
    return res.status(401).json({ code: 401, message: '登录已过期，请重新登录' });
  }
}

/**
 * 可选鉴权：有 token 且有效则填充 req.user，否则继续（不阻断）
 */
function optionalAuth(req, res, next) {
  const token = extractToken(req);
  if (!token) return next();
  try {
    const payload = jwt.verify(token, config.jwtSecret);
    const user = get(
      'SELECT id, nickname, avatar, phone, level_id, experience, balance, is_admin FROM users WHERE id = ?',
      [payload.userId]
    );
    if (user) {
      req.user = user;
      req.userId = user.id;
    }
  } catch (e) {
    // token 无效则忽略，继续
  }
  next();
}

/**
 * 权限控制（按会员等级 level_id 限定可访问模块）
 * 权限映射（来自原版）：
 *   level 2: products,orders,users,marketing,...
 *   level 3: ...,export
 *   level 4: orders,users,ai
 * @param {string} perm 逗号分隔的权限，例如 'orders' 
 */
function requirePermission(perm) {
  return (req, res, next) => {
    // is_admin 或超级管理员放行
    if (req.user && req.user.is_admin) return next();
    const userId = req.userId || (req.user && req.user.id);
    if (!userId) return res.status(401).json({ code: 401, message: '请先登录' });
    const row = get('SELECT level_id FROM users WHERE id = ?', [userId]);
    if (!row) return res.status(403).json({ code: 403, message: '用户不存在' });
    const level = row.level_id || 1;
    // level 2 及以上可访问业务模块
    if (level >= 2) return next();
    return res.status(403).json({ code: 403, message: '无权限访问' });
  };
}

module.exports = { authUser, authAdmin, optionalAuth, requirePermission, extractToken };
