const ROLE_HIERARCHY = {
    ADMIN: 100,
    EDITOR: 75,
    AUTHOR: 50,
    CLIENT: 25,
};
/** Check whether a user with the given role can perform an action on a resource. */
export function checkAccess(userRole, requiredRole) {
    return ROLE_HIERARCHY[userRole] >= ROLE_HIERARCHY[requiredRole];
}
/** Return the list of permissions granted to a role. */
export function getPermissionsForRole(role) {
    const permissions = [{ action: 'read', resource: '*' }];
    if (checkAccess(role, 'AUTHOR')) {
        permissions.push({ action: 'create', resource: '*' });
        permissions.push({ action: 'update', resource: 'own' });
    }
    if (checkAccess(role, 'EDITOR')) {
        permissions.push({ action: 'update', resource: '*' });
        permissions.push({ action: 'publish', resource: '*' });
    }
    if (checkAccess(role, 'ADMIN')) {
        permissions.push({ action: 'delete', resource: '*' });
    }
    return permissions;
}
/** Filter field definitions to only include those the user is allowed to read. */
export async function filterFieldsByRole(fields, user) {
    const result = {};
    for (const [name, field] of Object.entries(fields)) {
        if (!field.access?.read) {
            result[name] = field;
            continue;
        }
        const allowed = await field.access.read({ user });
        if (allowed) {
            result[name] = field;
        }
    }
    return result;
}
/** Filter incoming data to only include keys the user is allowed to update. */
export async function filterWritableFields(fields, data, user) {
    const result = {};
    for (const [key, value] of Object.entries(data)) {
        const field = fields[key];
        if (!field || !field.access?.update) {
            result[key] = value;
            continue;
        }
        const allowed = await field.access.update({ user });
        if (allowed) {
            result[key] = value;
        }
    }
    return result;
}
/**
 * Apply field-level access control to a data object.
 * For 'read': strips keys the user cannot read.
 * For 'write': strips keys the user cannot update.
 */
export async function applyFieldAccess(operation, fields, data, user) {
    const accessKey = operation === 'read' ? 'read' : 'update';
    const result = {};
    const SYSTEM_KEYS = new Set(['title', 'slug', 'status', '_aiScore', '_embedding', '_layout']);
    for (const [key, value] of Object.entries(data)) {
        const field = fields[key];
        if (!field) {
            if (operation === 'write' && !SYSTEM_KEYS.has(key)) {
                continue;
            }
            result[key] = value;
            continue;
        }
        const check = field.access?.[accessKey];
        if (!check) {
            result[key] = value;
            continue;
        }
        const allowed = await check({ user });
        if (allowed) {
            result[key] = value;
        }
    }
    return result;
}
//# sourceMappingURL=access.js.map