import jwt from 'jsonwebtoken';
import logger from '../../../utils/logger.js';
export class DeveloperAuthMiddleware {
    constructor(configManager) {
        this.authenticate = (req, res, next) => {
            try {
                const authHeader = req.headers.authorization;
                if (!authHeader || !authHeader.startsWith('Bearer ')) {
                    return res.status(401).json({
                        success: false,
                        message: '缺少开发者认证令牌'
                    });
                }
                const token = authHeader.substring(7);
                const jwtSecret = this.configManager.getJWTSecret();
                try {
                    const decoded = jwt.verify(token, jwtSecret);
                    if (decoded.type !== 'developer') {
                        return res.status(401).json({
                            success: false,
                            message: '无效的开发者令牌'
                        });
                    }
                    req.user = decoded;
                    next();
                }
                catch (jwtError) {
                    return res.status(401).json({
                        success: false,
                        message: '开发者令牌已过期或无效'
                    });
                }
            }
            catch (error) {
                logger.error('开发者认证中间件错误:', error);
                res.status(500).json({
                    success: false,
                    message: '服务器内部错误'
                });
            }
        };
        this.checkToken = (req, res, next) => {
            try {
                const developerHeader = req.headers['x-developer-token'];
                if (developerHeader && developerHeader.startsWith('Bearer ')) {
                    const token = developerHeader.substring(7);
                    try {
                        const jwtSecret = this.configManager.getJWTSecret();
                        const decoded = jwt.verify(token, jwtSecret);
                        if (decoded.type === 'developer') {
                            req.user = decoded;
                        }
                    }
                    catch {
                    }
                }
                next();
            }
            catch (error) {
                logger.error('检查开发者令牌错误:', error);
                next();
            }
        };
        this.configManager = configManager;
    }
}
