import jwt from 'jsonwebtoken';

const JWT_SECRET = process.env.JWT_SECRET || 'contract-approval-system-secret-key-2024';
const TOKEN_EXPIRY = '24h';

// 生成 JWT Token
export function generateToken(user) {
  return jwt.sign(
    {
      id: user.id,
      username: user.username,
      real_name: user.real_name,
      role: user.role,
      department_id: user.department_id,
    },
    JWT_SECRET,
    { expiresIn: TOKEN_EXPIRY }
  );
}

// 验证 JWT Token
export function verifyToken(token) {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch (error) {
    return null;
  }
}

// 从请求头获取用户信息
export function getUserFromRequest(request) {
  const authHeader = request.headers.get('Authorization');
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return null;
  }
  const token = authHeader.substring(7);
  return verifyToken(token);
}

// 检查是否有权限
export function checkRole(user, allowedRoles) {
  if (!user) return false;
  return allowedRoles.includes(user.role);
}

// 返回未授权响应
export function unauthorizedResponse() {
  return Response.json(
    { error: '未登录或登录已过期' },
    { status: 401 }
  );
}

// 返回无权限响应  
export function forbiddenResponse() {
  return Response.json(
    { error: '无权限访问' },
    { status: 403 }
  );
}
