"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.authMiddleware = authMiddleware;
exports.optionalAuth = optionalAuth;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const config_1 = require("../config");
const errorHandler_1 = require("./errorHandler");
async function authMiddleware(ctx, next) {
    const authHeader = ctx.get('Authorization');
    if (!authHeader) {
        throw new errorHandler_1.UnauthorizedError('缺少 Authorization 头');
    }
    const parts = authHeader.split(' ');
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
        throw new errorHandler_1.UnauthorizedError('Authorization 格式错误');
    }
    const token = parts[1];
    try {
        // 使用硬编码的secret，确保和generateToken一致
        const secret = 'my-jwt-secret-key-2024';
        const payload = jsonwebtoken_1.default.verify(token, secret);
        ctx.state.user = payload;
        await next();
    }
    catch (err) {
        const error = err;
        if (error.name === 'TokenExpiredError') {
            throw new errorHandler_1.UnauthorizedError('Token 已过期');
        }
        if (error.name === 'JsonWebTokenError') {
            throw new errorHandler_1.UnauthorizedError('Token 无效');
        }
        throw new errorHandler_1.AppError('认证失败', 401, 401);
    }
}
// 可选认证（允许未登录访问）
async function optionalAuth(ctx, next) {
    const authHeader = ctx.get('Authorization');
    if (authHeader) {
        const parts = authHeader.split(' ');
        if (parts.length === 2 && parts[0] === 'Bearer') {
            try {
                const payload = jsonwebtoken_1.default.verify(parts[1], config_1.config.jwt.secret);
                ctx.state.user = payload;
            }
            catch {
                // 忽略错误，继续执行
            }
        }
    }
    await next();
}
