"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupCms = void 0;
const change_case_1 = require("change-case");
const setupCms = async (config, [RoleResource, PermissionResource]) => {
    const { resources, orm } = config;
    const { em } = orm;
    const insertPermissions = await getPermissionsToInsert(resources, em, PermissionResource);
    if (insertPermissions.length > 0) {
        await em.persistAndFlush(insertPermissions.map(permission => em.create(PermissionResource.data.pascalCaseName, permission)));
    }
    // Insert default super admin role
    let superAdminRole = await em.findOne(RoleResource.data.pascalCaseName, {
        slug: 'super-admin'
    });
    const allPermissions = (await em.find(PermissionResource.data.pascalCaseName, {})).map((permission) => permission.id);
    if (!superAdminRole) {
        superAdminRole = em.create(RoleResource.data.pascalCaseName, {
            name: 'Super Admin',
            slug: 'super-admin',
            description: 'Manage the access and level of responsibility of all users on this network.',
            adminPermissions: allPermissions
        });
    }
    if (superAdminRole) {
        em.assign(superAdminRole, {
            adminPermissions: allPermissions
        });
    }
    await em.persistAndFlush(superAdminRole);
};
exports.setupCms = setupCms;
const getPermissionsToInsert = async (resources, em, permissionResource) => {
    const permissions = [];
    resources.forEach(resource => {
        ;
        ['create', 'index', 'update', 'delete'].forEach(operation => {
            permissions.push(`${operation}:${resource.data.slug}`);
        });
        resource.data.actions.forEach(action => {
            permissions.push(`run:${resource.data.slug}:${action.data.slug}`);
        });
        resource.data.permissions.forEach(permission => {
            permissions.push(permission);
        });
    });
    const existingPermissions = (await em.find(permissionResource.data.pascalCaseName, {
        slug: {
            $in: permissions
        }
    })).map(permission => permission.slug);
    const newPermissionsToCreate = permissions.filter(permission => !existingPermissions.includes(typeof permission === 'string' ? permission : permission.slug));
    return Array.from(new Set(newPermissionsToCreate)).map(permission => ({
        name: typeof permission === 'string'
            ? (0, change_case_1.sentenceCase)(permission.split(':').join(' '))
            : permission.name,
        slug: permission
    }));
};
