"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.canCreateChannel = canCreateChannel;
const sharingAccess_1 = require("../../enums/sharingAccess");
const platform_1 = require("../platform");
const constants_1 = require("../../../constants");
/**
 * Utility to determine if User has privileges to create a channel with the defined permissions
 * @deprecated replace with canCreateChannelV2 for v2 discussions
 * @export
 * @param channel
 * @param user
 * @returns {boolean}
 */
function canCreateChannel(channel, user = {}) {
    const { access, groups, orgs } = channel;
    return isAuthorizedToCreateByLegacyPermissions(user, {
        access,
        groups,
        orgs,
    });
}
// Once ACL usage is enforced, we will remove authorization by legacy permissions
function isAuthorizedToCreateByLegacyPermissions(user, channelParams) {
    const { username, groups: userGroups = [] } = user;
    const { access, groups: channelGroupIds = [], orgs: channelOrgs, } = channelParams;
    // ensure authenticated
    if (!username) {
        return false;
    }
    if (access === sharingAccess_1.SharingAccess.PRIVATE) {
        return canAllowGroupsLegacy(userGroups, channelGroupIds);
    }
    // public or org access
    return (canAllowGroupsLegacy(userGroups, channelGroupIds) &&
        isLegacyChannelOrgAdmin(user, channelOrgs));
}
function canAllowGroupsLegacy(userGroups, channelGroupIds) {
    return channelGroupIds.every((channelGroupId) => {
        const userGroup = userGroups.find((group) => group.id === channelGroupId);
        return (userGroup &&
            isMemberTypeAuthorized(userGroup) &&
            isGroupDiscussable(userGroup));
    });
}
function isMemberTypeAuthorized(userGroup) {
    const { userMembership: { memberType }, } = userGroup;
    return ["owner", "admin", "member"].includes(memberType);
}
function isGroupDiscussable(userGroup) {
    const { typeKeywords = [] } = userGroup;
    return !typeKeywords.includes(constants_1.CANNOT_DISCUSS);
}
function isLegacyChannelOrgAdmin(user, channelOrgs) {
    return (0, platform_1.isOrgAdmin)(user) && channelOrgs.includes(user.orgId);
}
//# sourceMappingURL=can-create-channel.js.map