const jwt = require('jsonwebtoken');
const { Admin } = require('../models');

const authSuper = async (req, res, next) => {
  const token = req.header('Authorization')?.replace('Bearer ', '');
  
  if (!token) {
    return res.status(401).json({ error: '未授权访问' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const admin = await Admin.findByPk(decoded.id);
    
    if (!admin || admin.role !== 'super') {
      return res.status(403).json({ error: '需要超级管理员权限' });
    }
    
    req.adminId = decoded.id;
    req.admin = admin;
    next();
  } catch (error) {
    res.status(401).json({ error: '无效的token' });
  }
};

module.exports = authSuper;
