"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.PermissionResolverService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("../../config");
const permission_catalog_1 = require("../../modules/access-control/permission-catalog");
let PermissionResolverService = class PermissionResolverService {
    constructor(db) {
        this.db = db;
    }
    isOwnerBypass(ctx) {
        return ctx.role === 'owner';
    }
    async getRolePermissionsMap(roleId) {
        const rows = await this.db.role_permissions.findMany({
            where: { role_id: roleId },
        });
        return rows.reduce((acc, row) => {
            acc[row.permission_key] = row.permission_value;
            return acc;
        }, {});
    }
    mergePermissionMap(slug, overrides = {}) {
        const defaults = (0, permission_catalog_1.getDefaultPermissionMap)(slug);
        const merged = { ...defaults };
        for (const [key, value] of Object.entries(overrides)) {
            if (permission_catalog_1.ALL_PERMISSION_KEYS.includes(key)) {
                merged[key] = value;
            }
        }
        return merged;
    }
    async resolveAccessRoleId(ctx) {
        if (ctx.role === 'owner') {
            const role = await this.db.access_roles.findFirst({
                where: { owner_id: ctx.owner_id, slug: 'owner' },
                select: { id: true },
            });
            return role?.id ?? null;
        }
        if (ctx.sub) {
            const member = await this.db.members.findFirst({
                where: { id: ctx.sub, owner_id: ctx.owner_id },
                select: { access_role_id: true, status: true },
            });
            if (!member || member.status !== 'active') {
                return null;
            }
            return member.access_role_id ?? null;
        }
        if (ctx.access_role_id) {
            return ctx.access_role_id;
        }
        const role = await this.db.access_roles.findFirst({
            where: { owner_id: ctx.owner_id, slug: ctx.role },
            select: { id: true },
        });
        return role?.id ?? null;
    }
    async resolveForUser(ctx) {
        if (this.isOwnerBypass(ctx)) {
            return (0, permission_catalog_1.getDefaultPermissionMap)('owner');
        }
        const accessRoleId = await this.resolveAccessRoleId(ctx);
        if (!accessRoleId) {
            const fallbackSlug = ctx.role === 'admin'
                ? 'admin'
                : ctx.role === 'owner'
                    ? 'owner'
                    : 'member';
            return (0, permission_catalog_1.getDefaultPermissionMap)(fallbackSlug);
        }
        const accessRole = await this.db.access_roles.findFirst({
            where: { id: accessRoleId, owner_id: ctx.owner_id },
            select: { id: true, slug: true },
        });
        if (!accessRole) {
            return (0, permission_catalog_1.getDefaultPermissionMap)('member');
        }
        const stored = await this.getRolePermissionsMap(accessRole.id);
        return this.mergePermissionMap(accessRole.slug, stored);
    }
};
exports.PermissionResolverService = PermissionResolverService;
exports.PermissionResolverService = PermissionResolverService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.DatabaseService])
], PermissionResolverService);
//# sourceMappingURL=permission-resolver.service.js.map