"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.authenticate = authenticate;
exports.optionalAuth = optionalAuth;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const env_1 = require("../config/env");
const error_handler_1 = require("./error-handler");
function authenticate(req, _res, next) {
    const header = req.headers.authorization;
    if (!header?.startsWith('Bearer ')) {
        throw new error_handler_1.AppError(401, 'Authentication required', 'AUTH_REQUIRED');
    }
    const token = header.slice(7);
    try {
        const payload = jsonwebtoken_1.default.verify(token, env_1.env.JWT_ACCESS_SECRET, { algorithms: ['HS256'] });
        req.user = {
            id: payload.id,
            email: payload.email,
            role: payload.role,
            roles: payload.roles || [payload.role], // Backwards compat: old JWTs without roles
        };
        next();
    }
    catch {
        throw new error_handler_1.AppError(401, 'Invalid or expired token', 'INVALID_TOKEN');
    }
}
function optionalAuth(req, _res, next) {
    const header = req.headers.authorization;
    if (!header?.startsWith('Bearer ')) {
        next();
        return;
    }
    const token = header.slice(7);
    try {
        const payload = jsonwebtoken_1.default.verify(token, env_1.env.JWT_ACCESS_SECRET, { algorithms: ['HS256'] });
        req.user = {
            id: payload.id,
            email: payload.email,
            role: payload.role,
            roles: payload.roles || [payload.role],
        };
    }
    catch {
        // Token invalid — continue without user
    }
    next();
}
//# sourceMappingURL=auth.middleware.js.map