"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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoleGuard = void 0;
const api_1 = require("@hed-hog/api");
const api_locale_1 = require("@hed-hog/api-locale");
const api_prisma_1 = require("@hed-hog/api-prisma");
const common_1 = require("@nestjs/common");
const constants_1 = require("@nestjs/common/constants");
const core_1 = require("@nestjs/core");
let RoleGuard = class RoleGuard {
    constructor(reflector, prisma) {
        this.reflector = reflector;
        this.prisma = prisma;
        this.forcePasswordResetAllowedRoutes = new Set([
            'PUT /profile/change-password',
            'GET /auth/verify',
        ]);
    }
    async canActivate(context) {
        var _a;
        const isPublic = this.reflector.getAllAndOverride(api_1.IS_PUBLIC_KEY, [
            context.getHandler(),
            context.getClass(),
        ]);
        if (isPublic) {
            return true;
        }
        const withNoRole = this.reflector.getAllAndOverride(api_1.WITH_NO_ROLE, [
            context.getHandler(),
            context.getClass(),
        ]);
        if (withNoRole) {
            // @NoRole() — user must be authenticated but no specific role is required
            return true;
        }
        const withRole = this.reflector.getAllAndOverride(api_1.WITH_ROLE, [
            context.getHandler(),
            context.getClass(),
        ]);
        if (!withRole) {
            return true;
        }
        const request = context.switchToHttp().getRequest();
        const controller = context.getClass();
        const handler = context.getHandler();
        const controllerPath = this.reflector.get('path', controller) || '';
        const methodPath = this.reflector.get('path', handler) || '';
        const requestMethod = this.reflector.get(constants_1.METHOD_METADATA, handler);
        let fullPath = `/${controllerPath}/${methodPath}`.replace(/\/+/g, '/');
        if (fullPath.endsWith('/')) {
            fullPath = fullPath.slice(0, -1);
        }
        const token = this.extractTokenFromHeader(request);
        if (!token) {
            const locale = request['locale'] || 'en';
            throw new common_1.UnauthorizedException((0, api_locale_1.getLocaleText)('accessDenied', locale, 'Access denied.'));
        }
        const userId = (_a = request === null || request === void 0 ? void 0 : request.auth) === null || _a === void 0 ? void 0 : _a.sub;
        let httpMethod;
        switch (requestMethod) {
            case common_1.RequestMethod.GET:
                httpMethod = 'GET';
                break;
            case common_1.RequestMethod.POST:
                httpMethod = 'POST';
                break;
            case common_1.RequestMethod.PUT:
                httpMethod = 'PUT';
                break;
            case common_1.RequestMethod.DELETE:
                httpMethod = 'DELETE';
                break;
            case common_1.RequestMethod.PATCH:
                httpMethod = 'PATCH';
                break;
            case common_1.RequestMethod.OPTIONS:
                httpMethod = 'OPTIONS';
                break;
            case common_1.RequestMethod.HEAD:
                httpMethod = 'HEAD';
                break;
            case common_1.RequestMethod.ALL:
                httpMethod = 'ALL';
                break;
        }
        const route = await this.prisma.route.count({
            where: {
                method: httpMethod,
                url: fullPath,
                role_route: {
                    some: {
                        role: {
                            role_user: {
                                some: {
                                    user_id: userId,
                                }
                            }
                        }
                    }
                },
            },
        });
        if (route !== 1) {
            const locale = request['locale'] || 'en';
            const message = (0, api_locale_1.getLocaleText)('accessDenied', locale, 'Access denied. User does not have permission to access {{method}} {{path}}')
                .replace('{{method}}', httpMethod)
                .replace('{{path}}', fullPath);
            throw new common_1.ForbiddenException(message);
        }
        const hasPendingPasswordReset = await this.prisma.user_credential.findFirst({
            where: {
                user_id: userId,
                type: 'password',
                requires_reset: true,
                revoked_at: null,
            },
            select: { id: true },
        });
        if (hasPendingPasswordReset &&
            !this.forcePasswordResetAllowedRoutes.has(`${httpMethod} ${fullPath}`)) {
            const locale = request['locale'] || 'en';
            throw new common_1.UnauthorizedException((0, api_locale_1.getLocaleText)('profile.changePassword.required', locale, 'Password update required before accessing this resource.'));
        }
        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.RoleGuard = RoleGuard;
exports.RoleGuard = RoleGuard = __decorate([
    (0, common_1.Injectable)(),
    __param(1, (0, common_1.Inject)((0, common_1.forwardRef)(() => api_prisma_1.PrismaService))),
    __metadata("design:paramtypes", [core_1.Reflector,
        api_prisma_1.PrismaService])
], RoleGuard);
//# sourceMappingURL=role.guard.js.map