import { Sequelize, WhereOptions, FindOptions, literal, fn, col, Op } from "sequelize";
import Models from "../models";
import { LocalizedContent } from "../../utils/contentGenerator";
import { AppError } from "../../utils/errors";
import Moment from "moment-timezone";
import { Common } from "../../utils/common"
import _, { trimStart } from 'lodash';
import { ROLE } from "../config/constants"


const roleAttributes: AttributeElement[] = [
    'id', 'code', 'status', 'createdAt', 'updatedAt',
    [literal('(case when `content`.name is not null then `content`.name else `defaultContent`.name END)'), 'name'],
    [literal('(case when `content`.description is not null then `content`.description else `defaultContent`.description END)'), 'description'],
    [literal('(case when `content`.description_text is not null then `content`.description_text else `defaultContent`.description_text END)'), 'descriptionText']
];

const rolePermissionAttributes: AttributeElement[] = [
    'id', 'code', [literal('(case when `rolePermissions->content`.name is not null then `rolePermissions->content`.name else `rolePermissions->defaultContent`.name END)'), 'name']
]

const permissionAttributes: AttributeElement[] = [
    'id', 'code', [literal('(case when `content`.name is not null then `content`.name else `defaultContent`.name END)'), 'name']
]

const authorAttributes: AttributeElement[] = [
    'id', 'onlineStatus',
    [literal('`author->userProfile`.`name`'), 'name'],
    [
        literal(`(
              SELECT JSON_OBJECT(
                'id', a.id,
                'fileName', a.file_name,
                'uniqueName', a.unique_name,
                'filePath', CONCAT('${process.env.PROTOCOL}://', '${process.env.API_HOST}', '/attachment/', a.unique_name),
                'cdnUrl', CONCAT('${process.env.CDN_PATH}', '/attachment/', a.unique_name)
              )
              FROM user_profile as up
              JOIN attachments as a ON up.profile_image_id = a.id
              WHERE up.user_id = author.id
              LIMIT 1
            )`),
        'profileImage'
    ]
];

const updatedByAttributes: AttributeElement[] = [
    'id', 'onlineStatus',
    [literal('`updatedBy->userProfile`.`name`'), 'name'],
    [
        literal(`(
              SELECT JSON_OBJECT(
                'id', a.id,
                'fileName', a.file_name,
                'uniqueName', a.unique_name,
                'filePath', CONCAT('${process.env.PROTOCOL}://', '${process.env.API_HOST}', '/attachment/', a.unique_name),
                'cdnUrl', CONCAT('${process.env.CDN_PATH}', '/attachment/', a.unique_name)
              )
              FROM user_profile as up
              JOIN attachments as a ON up.profile_image_id = a.id
              WHERE up.user_id = author.id
              LIMIT 1
            )`),
        'profileImage'
    ]
];

export class RoleDao {
    private accountId: number | null;
    private userId: number | null;
    private language: string;
    private scope: string[] | null;
    private config: userConfig | null;
    constructor(
        private options: {
            language: string;
            scope: string[] | null;
            accountId: number | null;
            userId: number | null;
            config: userConfig | null;
        } = {
                language: process.env.DEFAULT_LANGUAGE_CODE!,
                scope: null,
                config: null,
                userId: null,
                accountId: null,
            }
    ) {
        this.language = options.language;
        this.scope = options.scope ?? [];
        this.config = options.config ?? null;
        this.userId = options.userId ?? null
        this.accountId = options.accountId ?? null
    }
    // set role sortOrder
    setSortOrder = async (data: RoleSetSortOrderDaoInput, options: DaoOptions = {}): Promise<boolean> => {
        const { id, before = null, after = null } = data;
        const { transaction } = options;
        try {
            let roleData = await Models.Role.findOne({ attributes: ['id', 'sortOrder'], where: { id: id, accountId: this.accountId, isRevision: false } });
            if (roleData) {
                if (before || after) {
                    let locationData = await Models.Role.findOne({ attributes: ['id', 'sortOrder'], where: { id: before ? before : after, isRevision: false } });
                    if (!locationData) {
                        return false;
                    }
                    if (roleData.sortOrder < locationData.sortOrder) {
                        await Models.Role.decrement('sortOrder', {
                            by: 1,
                            where: {
                                accountId: this.accountId,
                                [Op.and]: [
                                    { sortOrder: { [Op.gt]: roleData.sortOrder } },
                                    before ? { sortOrder: { [Op.lt]: locationData.sortOrder } } : { sortOrder: { [Op.lte]: locationData.sortOrder } }
                                ]
                            },
                            transaction: transaction
                        });
                        await Models.Role.update(before ? { sortOrder: locationData.sortOrder - 1 } : { sortOrder: locationData.sortOrder }, { where: { id: roleData.id }, transaction: transaction });
                    } else if (roleData.sortOrder > locationData.sortOrder) {
                        await Models.Role.increment('sortOrder', {
                            by: 1,
                            where: {
                                accountId: this.accountId,
                                [Op.and]: [
                                    before ? { sortOrder: { [Op.gte]: locationData.sortOrder } } : { sortOrder: { [Op.gt]: locationData.sortOrder } },
                                    { sortOrder: { [Op.lt]: roleData.sortOrder } }
                                ]
                            },
                            transaction: transaction
                        });
                        await Models.Role.update(before ? { sortOrder: locationData.sortOrder } : { sortOrder: locationData.sortOrder + 1 }, { where: { id: roleData.id }, transaction: transaction });
                    }
                }
                else {
                    let maxSortOrder = await Models.Role.max('sortOrder', { where: { accountId: this.accountId } });
                    await Models.Quote.update(
                        { sortOrder: (maxSortOrder || 0) + 1 }, // default to 1 if no max found
                        { where: { id: roleData.id, accountId: this.accountId }, transaction: transaction }
                    );
                }
                return true;
            } else {
                return false;
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }
    // Get full entity object for manipulation
    private getFullObject = async (id: number, options: DaoOptions = {}) => {
        try {
            let Role = await Models.Role.findOne({
                where: { id: id },
                include: [{ model: Models.RoleContent, as: 'roleContents' }],
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(Role))
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'ERROR_WHILE_GETTING_FULL_DATA', err);
        }
    }

    // Generate revision of role prior to update and delete functions.
    private storeRevision = async (id: number, options: DaoOptions = {}) => {
        try {
            let Object: RoleInterface = await this.getFullObject(id, options);
            let revisonObject = JSON.parse(JSON.stringify(Object));
            let revisionId = revisonObject.id;
            revisonObject = _.omit(revisonObject, ['id', 'createdAt', 'updatedAt', 'deletedAt']);
            revisonObject.isRevision = true;
            revisonObject.code = revisonObject.code + '-' + Moment().toISOString();
            revisonObject.revisionId = revisionId;
            for (const key in revisonObject.roleContents) {
                revisonObject.roleContents[key] = _.omit(revisonObject.roleContents[key], ['id', 'roleId'])
            }
            let revision = await Models.Role.create(revisonObject, { include: [{ model: Models.RoleContent, as: 'roleContents' }], transaction: options.transaction });
            if (revision)
                return revision;
            else {
                throw new AppError(400, 'ERROR_WHILE_CREATING_REVISION', {});
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get association for the entity
    private includeAssociations = (fullInfo: boolean = false, includePermission: boolean = true): IncludeOption[] => {
        const includeModels: IncludeOption[] = [
            {
                attributes: [],
                model: Models.RoleContent,
                as: 'content',
                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: this.language } }]
            },
            {
                attributes: [],
                model: Models.RoleContent,
                as: 'defaultContent',
                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: process.env.DEFAULT_LANGUAGE_CODE } }]
            }
        ];
        if (includePermission) {
            includeModels.push({
                attributes: rolePermissionAttributes,
                model: Models.Permission,
                as: "rolePermissions",
                required: false,
                include: [
                    {
                        attributes: [],
                        model: Models.PermissionContent,
                        as: 'content',
                        include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: this.language } }]
                    },
                    {
                        attributes: [],
                        model: Models.PermissionContent,
                        as: 'defaultContent',
                        include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: process.env.DEFAULT_LANGUAGE_CODE } }]
                    },
                ],
                through: { attributes: [] }
            })
        }
        if (fullInfo) {
            includeModels.push(
                {
                    attributes: authorAttributes,
                    model: Models.User,
                    as: 'author',
                    include: [{ attributes: [], model: Models.UserProfile, as: 'userProfile', include: [{ model: Models.Attachment, as: "profileImage" }] }]
                },
                {
                    attributes: updatedByAttributes,
                    model: Models.User,
                    as: 'updatedBy',
                    include: [{ attributes: [], model: Models.UserProfile, as: 'userProfile', include: [{ model: Models.Attachment, as: "profileImage" }] }]
                }
            );
        }
        return includeModels;
    }

    // get role
    getRole = async (data: RoleGetDaoInput, options: DaoOptions = {}) => {
        try {
            const { id = null, code = null, expanded = true, paranoid = true } = data;
            const role = await Models.Role.findOne({
                attributes: roleAttributes,
                where: { ...(id ? { id } : code ? { code } : {}), ...{ [Op.or]: [{ accountId: this.accountId }, { accountId: null }] } },
                include: this.includeAssociations(expanded),
                paranoid: paranoid,
                subQuery: false,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(role));
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get role by id
    getRoleById = async (data: RoleGetByIdDaoInput, options: DaoOptions = {}) => {
        try {
            const getRoleInput: RoleGetDaoInput = { id: data.id, code: null, expanded: data.expanded ?? true, paranoid: data.paranoid ?? true };
            return await this.getRole(getRoleInput, options);
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get role by code
    getRoleByCode = async (data: RoleGetByCodeDaoInput, options: DaoOptions = {}) => {
        try {
            const getRoleInput: RoleGetDaoInput = { id: null, code: data.code, expanded: data.expanded ?? true, paranoid: data.paranoid ?? true };
            return await this.getRole(getRoleInput, options);
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // check if role exists by code
    doExistsByCode = async (data: RoleDoExistsByCodeDaoInput, options: DaoOptions = {}): Promise<RoleInterface | false> => {
        try {
            const { code, excludeId = null } = data;
            const role = await Models.Role.findOne({
                attributes: ['id'],
                where: { ...(excludeId ? { id: { [Op.ne]: excludeId } } : {}), code: code, accountId: this.accountId, isRevision: false },
                transaction: options.transaction
            });
            return role?.id ? role : false;
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // check if role exists by id
    doExistsById = async (data: RoleDoExistsByIdDaoInput, options: DaoOptions = {}): Promise<RoleInterface | false> => {
        try {
            const { id, includeRevision = false } = data;
            const role = await Models.Role.findOne({
                attributes: ['id'],
                where: { id: id, accountId: this.accountId, isRevision: includeRevision },
                transaction: options.transaction
            });
            return role?.id ? role : false;
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // create a new role
    create = async (data: RoleCreateDaoInput, options: DaoOptions = {}) => {
        try {
            const { roleObj, roleContentObj, permissionIds, languages } = data;
            const roleContents: RoleContentObject[] = LocalizedContent.generate(roleContentObj, languages) as unknown as RoleContentObject[];
            const roleObject: RoleDataObject = { ...roleObj, userId: this.userId, accountId: this.accountId, roleContents: roleContents };
            let role = await Models.Role.create(roleObject, {
                include: [{ model: Models.RoleContent, as: 'roleContents' }],
                transaction: options.transaction
            });
            if (permissionIds) {
                await role.setRolePermissions(permissionIds, { transaction: options.transaction });
            }
            return role.id;
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // update content type
    update = async (data: RoleUpdateDaoInput, options: DaoOptions = {}) => {
        try {
            const { id, roleObj, roleContentObj, permissionIds, languages } = data;
            await this.storeRevision(id, options);
            const roleContents: RoleContentObject[] = LocalizedContent.generate(roleContentObj, languages) as unknown as RoleContentObject[];
            // check if content exists in requested language
            let roleToUpdate = await Models.Role.findOne({ where: { id: id, accountId: this.accountId } });
            if (roleToUpdate) {
                roleToUpdate.update(roleObj, { transaction: options.transaction });
                let verification = await Models.RoleContent.findOne({ where: { roleId: id, languageId: languages.requested.id }, transaction: options.transaction });
                if (verification) { // update if content exists in the requested language
                    // generate revision for the existing state
                    let roleContent: RoleContentObject = { ...roleContentObj, ...{ languageId: languages.requested.id, roleId: id } }
                    await Models.RoleContent.update(roleContent, { where: { id: verification.id }, transaction: options.transaction })

                } else { // create if content does not exists in the requested language
                    let roleContent: RoleContentObject = { ...roleContentObj, ...{ languageId: languages.requested.id, roleId: id } }
                    await Models.RoleContent.create(roleContent, { transaction: options.transaction })
                }
                if (permissionIds) {
                    await roleToUpdate.setRolePermissions(permissionIds, { transaction: options.transaction });
                } else {
                    await roleToUpdate.setRolePermissions([], { transaction: options.transaction });
                }
                return;
            } else {
                throw new AppError(404, 'ROLE_NOT_FOUND', { id: 'ROLE_NOT_FOUND' });
            }
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // delete content type
    delete = async (data: RoleDeleteDaoInput, options: DaoOptions = {}) => {
        try {
            const { id } = data;
            const getRoleByIdInput: RoleGetByIdDaoInput = { id };
            let role = await this.getRoleById(getRoleByIdInput, options);
            let code = role.code + '-' + Moment().toISOString();
            await Models.Role.update({ lastUpdatedBy: this.userId, code: code }, { where: { id: id, accountId: this.accountId }, transaction: options.transaction });
            await Models.Role.destroy({ where: { id: id, accountId: this.accountId }, transaction: options.transaction });
            return;
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // Build order by clause
    private buildOrderBy = (field: string, direction: string = 'desc') => {
        switch (field) {
            case 'sort-order':
                return [['sortOrder', direction]];
            case 'name':
                return [[literal(`name`), direction]];
            case 'id':
                return [['id', direction]];
            default:
                // Fallback to default order
                return [
                    ['id', 'ASC']
                ];
        }
    }

    // Build filter
    private buildFilter = (where: WhereOptions & { [Op.and]: any[] }, searchText: string | null, status: number | null) => {
        let alphaString = '';
        let specialString = '';
        if (searchText) {
            let searchData: searchText = Common.prepareSearchText(searchText);
            if (searchData.alphaString) {
                alphaString = '*' + searchData.alphaString + '*'
            } if (searchData.specialString) {
                specialString = searchData.specialString
            }
            if (alphaString) {
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`defaultContent`.`name`,`defaultContent`.`description_text`) AGAINST(:alphaString IN BOOLEAN MODE)'));
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`content`.`name`,`content`.`description_text`) AGAINST(:alphaString IN BOOLEAN MODE)'));
            } if (specialString) {
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`defaultContent`.`name`,`defaultContent`.`description_text`) AGAINST(:alphaString IN BOOLEAN MODE)'));
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`content`.`name`,`defaultContent`.`content`) AGAINST(:alphaString IN BOOLEAN MODE)'));
            }
        }
        if (status != null) {
            where = { ...where, status: status }
        }
        return { where: where, replacements: { alphaString: alphaString, specialString: specialString } }
    }

    // list roles with pagination
    getRoleList = async (data: RoleGetRoleListDaoInput, options: DaoOptions = {}) => {
        try {
            const { listRequest } = data;
            const { page, perPage, searchText, sortBy, sortDirection, status } = listRequest
            let offset = (page - 1) * perPage;
            let where: WhereOptions & { [Op.and]: any[] } = { isRevision: false, [Op.and]: [], [Op.or]: [{ accountId: this.accountId }, { accountId: null }] };
            let applyfilter = this.buildFilter(where, searchText, status);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const roles = await Models.Role.findAndCountAll({
                attributes: roleAttributes,
                where: applyfilter.where,
                include: this.includeAssociations(false, false),
                replacements: applyfilter.replacements,
                offset: offset,
                limit: perPage,
                subQuery: false,
                order: orderBy,
                transaction: options.transaction
            });
            const roleIds = roles.rows.map((r: any) => r.id);
            const rolePermissions = await Models.Role.findAll({
                attributes: ['id'],
                where: { id: roleIds },
                include: [
                    {
                        model: Models.Permission,
                        as: "rolePermissions",
                        attributes: rolePermissionAttributes,
                        include: [
                            {
                                attributes: [],
                                model: Models.PermissionContent,
                                as: 'content',
                                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: this.language } }]
                            },
                            {
                                attributes: [],
                                model: Models.PermissionContent,
                                as: 'defaultContent',
                                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: process.env.DEFAULT_LANGUAGE_CODE } }]
                            },
                        ],
                        through: { attributes: [] }
                    }
                ],
                transaction: options.transaction
            });
            const permissionMap = new Map();
            rolePermissions.forEach((role: any) => {
                permissionMap.set(role.id, role.rolePermissions);
            });
            const finalRoles = roles.rows.map((role: any) => {
                const roleJson = role.toJSON();
                roleJson.rolePermissions = permissionMap.get(role.id) || [];
                return roleJson;
            });
            roles.rows = finalRoles;
            return JSON.parse(JSON.stringify(roles));
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // list all roles
    getAllRoles = async (data: RoleGetAllRolesDaoInput, options: DaoOptions = {}) => {
        try {
            const { listRequest } = data;
            const { searchText, sortBy, sortDirection, status } = listRequest
            let where: WhereOptions & { [Op.and]: any[] } = { accountId: this.accountId, isRevision: false, [Op.and]: [], [Op.or]: [{ accountId: this.accountId }, { accountId: null }] };
            let applyfilter = this.buildFilter(where, searchText, status);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const roles = await Models.Role.findAll({
                attributes: roleAttributes,
                where: applyfilter.where,
                replacements: applyfilter.replacements,
                include: this.includeAssociations(false),
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(roles));
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // list roles revisions
    getRoleRevisionList = async (data: RoleGetRoleRevisionListDaoInput, options: DaoOptions = {}) => {
        try {
            const { id, listRequest } = data;
            const { page, perPage, searchText, sortBy, sortDirection, status } = listRequest
            let offset = (page - 1) * perPage;
            let where: WhereOptions & { [Op.and]: any[] } = { accountId: this.accountId, isRevision: true, revisionId: id, [Op.and]: [], [Op.or]: [{ accountId: this.accountId }, { accountId: null }] };
            let applyfilter = this.buildFilter(where, searchText, status);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const roles = await Models.Role.findAndCountAll({
                attributes: roleAttributes,
                where: applyfilter.where,
                include: this.includeAssociations(true, false),
                replacements: applyfilter.replacements,
                offset: offset,
                limit: perPage,
                order: orderBy,
                transaction: options.transaction
            });
            const roleIds = roles.rows.map((r: any) => r.id);
            const rolePermissions = await Models.Role.findAll({
                attributes: ['id'],
                where: { id: roleIds },
                include: [
                    {
                        model: Models.Permission,
                        as: "rolePermissions",
                        attributes: rolePermissionAttributes,
                        include: [
                            {
                                attributes: [],
                                model: Models.PermissionContent,
                                as: 'content',
                                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: this.language } }]
                            },
                            {
                                attributes: [],
                                model: Models.PermissionContent,
                                as: 'defaultContent',
                                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: process.env.DEFAULT_LANGUAGE_CODE } }]
                            },
                        ],
                        through: { attributes: [] }
                    }
                ],
                transaction: options.transaction
            });
            const permissionMap = new Map();
            rolePermissions.forEach((role: any) => {
                permissionMap.set(role.id, role.rolePermissions);
            });
            const finalRoles = roles.rows.map((role: any) => {
                const roleJson = role.toJSON();
                roleJson.rolePermissions = permissionMap.get(role.id) || [];
                return roleJson;
            });
            roles.rows = finalRoles;
            return JSON.parse(JSON.stringify(roles));
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // restore revision for roles
    restoreRevision = async (data: RoleRestoreRevisionDaoInput, options: DaoOptions = {}) => {
        try {
            const { id } = data;
            const checkRoleRevisionInput: RoleDoExistsByIdDaoInput = { id, includeRevision: true };
            if (await this.doExistsById(checkRoleRevisionInput, options)) {
                // get full revision Data
                let Object: RoleInterface = await this.getFullObject(id, options);
                if (Object && Object.revisionId) {
                    // create new revision from existing state
                    await this.storeRevision(Object.revisionId, options);
                    let revisonObject = JSON.parse(JSON.stringify(Object));
                    // remove unnecessary data from object
                    revisonObject = _.omit(revisonObject, ['id', 'createdAt', 'updatedAt', 'deletedAt']);
                    // remove revision updates
                    // revisonObject.code = revisonObject.code.split('-').slice(0, -1).join('-');
                    // update entity type
                    await Models.Role.update({ lastUpdatedBy: this.userId }, { where: { id: revisonObject.revisionId }, transaction: options.transaction });
                    // update entity type content
                    if (revisonObject.roleContents && revisonObject.roleContents.length) {
                        for (let content of revisonObject.roleContents) {
                            await Models.RoleContent.upsert({ name: content.name, languageId: content.languageId, roleId: Object.revisionId }, { transaction: options.transaction });
                        }
                    }
                    return Object.revisionId;
                } else {
                    throw new AppError(400, 'REQUESTED_ENTITY_IS_NOT_A_REVISION', { id: 'REQUESTED_ENTITY_IS_NOT_A_REVISION' });
                }
            } else {
                throw new AppError(404, 'ROLE_NOT_FOUND', { id: 'ROLE_NOT_FOUND' });

            }
        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    getDafaultRoles = async (): Promise<number[]> => {
        try {
            let defaultRoles = await Models.Role.findAll({ attributes: ['id'], where: { status: ROLE.STATUS.ACTIVE, isDefault: 1, [Op.or]: [{ accountId: null }, { accountId: this.accountId }] } });
            const roleIds: number[] = defaultRoles.map((role: { id: number }) => { return role.id });
            return roleIds;

        } catch (err) {
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }
    // update role status
    updateStatus = async (data: RoleUpdateStatusDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            await Models.Role.update({ status: data.status }, { where: { id: data.id, accountId: this.accountId }, transaction: options.transaction });
            return;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get staff roles
    getStaffRoles = async (): Promise<number[]> => {
        try {
            let staffRoles: { id: number }[] = await Models.Role.findAll({ attributes: ['id'], where: { code: { [Op.notIn]: ['user','influencer'] } } });
            let staffRoleIds = [];
            for (let staffRole of staffRoles) {
                staffRoleIds.push(staffRole.id)
            }
            return staffRoleIds;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get staff roles
    getUserRoles = async (): Promise<number[]> => {
        try {
            let staffRoles: { id: number }[] = await Models.Role.findAll({ attributes: ['id'], where: { code: { [Op.in]: ['user','influencer'] }, accountId: null } });
            let staffRoleIds = [];
            for (let staffRole of staffRoles) {
                staffRoleIds.push(staffRole.id)
            }
            return staffRoleIds;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }
}
