"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthGuard = void 0;
const api_1 = require("@hed-hog/api");
const api_locale_1 = require("@hed-hog/api-locale");
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const token_service_1 = require("../../token/token.service");
let AuthGuard = class AuthGuard {
    constructor(token, reflector) {
        this.token = token;
        this.reflector = reflector;
    }
    async canActivate(context) {
        const isPublic = this.reflector.getAllAndOverride(api_1.IS_PUBLIC_KEY, [
            context.getHandler(),
            context.getClass(),
        ]);
        const withRole = this.reflector.getAllAndOverride(api_1.WITH_ROLE, [
            context.getHandler(),
            context.getClass(),
        ]);
        const withNoRole = this.reflector.getAllAndOverride(api_1.WITH_NO_ROLE, [
            context.getHandler(),
            context.getClass(),
        ]);
        const request = context.switchToHttp().getRequest();
        const token = this.extractTokenFromHeader(request);
        const locale = request.headers['locale'] || request.headers['accept-language'] || 'en';
        // If endpoint requires role/authentication and no token provided
        if (!token) {
            if (isPublic) {
                return true;
            }
            else if (withNoRole) {
                // @NoRole() requires authentication but no specific role — token is mandatory
                throw new common_1.UnauthorizedException((0, api_locale_1.getLocaleText)('accessDenied', locale, 'Access denied.'));
            }
            else if (withRole) {
                // @Role() decorator requires authentication
                throw new common_1.UnauthorizedException((0, api_locale_1.getLocaleText)('accessDenied', locale, 'Access denied.'));
            }
            else {
                // No explicit decorator, default behavior (deny)
                throw new common_1.UnauthorizedException((0, api_locale_1.getLocaleText)('accessDenied', locale, 'Access denied.'));
            }
        }
        try {
            const payload = await this.token.verify(locale, token);
            request['auth'] = payload;
        }
        catch (error) {
            if (isPublic) {
                return true;
            }
            else {
                // Return proper 401 status with clear message for JWT errors
                const message = (error === null || error === void 0 ? void 0 : error.message) || (error === null || error === void 0 ? void 0 : error.name) || 'Unauthorized';
                throw new common_1.UnauthorizedException(message);
            }
        }
        return true;
    }
    extractTokenFromHeader(request) {
        var _a, _b;
        const [type, token] = (_b = (_a = request.headers.authorization) === null || _a === void 0 ? void 0 : _a.split(' ')) !== null && _b !== void 0 ? _b : [];
        return type === 'Bearer' ? token : undefined;
    }
};
exports.AuthGuard = AuthGuard;
exports.AuthGuard = AuthGuard = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [token_service_1.TokenService,
        core_1.Reflector])
], AuthGuard);
//# sourceMappingURL=auth.guard.js.map