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 _ from 'lodash';

const permissionAttributes: 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 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 permissionCategoryAttributes: AttributeElement[] = [
    'id', 'code', [literal('(case when `permissionCategory->content`.name is not null then `permissionCategory->content`.name else `permissionCategory->defaultContent`.name END)'), 'name'],
];

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 PermissionDao {
    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 permission sortOrder
    setSortOrder = async (data: PermissionSetSortOrderDaoInput, options: DaoOptions = {}): Promise<boolean> => {
        const { id, before = null, after = null } = data;
        const { transaction } = options;
        try {
            let permissionData = await Models.Permission.findOne({ attributes: ['id', 'sortOrder'], where: { id: id, isRevision: false }, transaction });
            if (permissionData) {
                if (before || after) {
                    let locationData = await Models.Permission.findOne({ attributes: ['id', 'sortOrder'], where: { id: before ? before : after, isRevision: false }, transaction });
                    if (!locationData) {
                        return false;
                    }
                    if (permissionData.sortOrder < locationData.sortOrder) {
                        await Models.Permission.decrement('sortOrder', {
                            by: 1,
                            where: {
                                [Op.and]: [
                                    { sortOrder: { [Op.gt]: permissionData.sortOrder } },
                                    before ? { sortOrder: { [Op.lt]: locationData.sortOrder } } : { sortOrder: { [Op.lte]: locationData.sortOrder } }
                                ]
                            },
                            transaction
                        });
                        await Models.Permission.update(before ? { sortOrder: locationData.sortOrder - 1 } : { sortOrder: locationData.sortOrder }, { where: { id: permissionData.id }, transaction });
                    } else if (permissionData.sortOrder > locationData.sortOrder) {
                        await Models.Permission.increment('sortOrder', {
                            by: 1,
                            where: {
                                [Op.and]: [
                                    before ? { sortOrder: { [Op.gte]: locationData.sortOrder } } : { sortOrder: { [Op.gt]: locationData.sortOrder } },
                                    { sortOrder: { [Op.lt]: permissionData.sortOrder } }
                                ]
                            },
                            transaction
                        });
                        await Models.Permission.update(before ? { sortOrder: locationData.sortOrder } : { sortOrder: locationData.sortOrder + 1 }, { where: { id: permissionData.id }, transaction });
                    }
                }
                else {
                    let maxSortOrder = await Models.Permission.max('sortOrder', { transaction });
                    await Models.Permission.update(
                        { sortOrder: (maxSortOrder || 0) + 1 },
                        { where: { id: permissionData.id }, 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 permission object
    private getFullObject = async (id: number, options: DaoOptions = {}): Promise<PermissionInterface> => {
        try {
            let Permission = await Models.Permission.findOne({
                where: { id: id },
                include: [{ model: Models.PermissionContent, as: 'permissionContents' }],
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(Permission));
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'ERROR_WHILE_GETTING_FULL_DATA', err);
        }
    }

    // Generate revision of permission prior to update and delete functions.
    private storeRevision = async (id: number, options: DaoOptions = {}): Promise<PermissionInterface> => {
        try {
            let Object: PermissionInterface = 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.permissionContents) {
                revisonObject.permissionContents[key] = _.omit(revisonObject.permissionContents[key], ['id', 'permissionId']);
            }
            let revision = await Models.Permission.create(revisonObject, { include: [{ model: Models.PermissionContent, as: 'permissionContents' }], 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): IncludeOption[] => {
        const includeModels: IncludeOption[] = [
            {
                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 } }]
            }
        ];
        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" }] }]
                },
                {
                    attributes: permissionCategoryAttributes,
                    model: Models.Category,
                    as: 'permissionCategory',
                    include: [
                        {
                            attributes: [],
                            model: Models.CategoryContent,
                            as: 'content',
                            include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: this.language } }]
                        },
                        {
                            attributes: [],
                            model: Models.CategoryContent,
                            as: 'defaultContent',
                            include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: process.env.DEFAULT_LANGUAGE_CODE } }]
                        }
                    ]
                }
            );
        }
        return includeModels;
    }

    // get permission
    getPermission = async (data: PermissionGetDaoInput, options: DaoOptions = {}): Promise<PermissionObjectInteface> => {
        try {
            const { id = null, code = null, paranoid = false } = data;
            const permission = await Models.Permission.findOne({
                attributes: permissionAttributes,
                where: id ? { id } : code ? { code } : undefined,
                include: this.includeAssociations(true),
                paranoid: paranoid,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(permission)) as unknown as PermissionObjectInteface;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get permissions
    getPermissions = async (data: PermissionGetPermissionsDaoInput, options: DaoOptions = {}): Promise<PermissionObjectInteface[]> => {
        try {
            const { ids, fullObject, paranoid = true } = data;
            const permissions = await Models.Permission.findAll({
                attributes: permissionAttributes,
                where: { ...(ids ? { id: ids } : {}) },
                include: this.includeAssociations(fullObject),
                paranoid: paranoid,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(permissions)) as unknown as PermissionObjectInteface[];
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get permission by id
    getPermissionById = async (data: PermissionGetByIdDaoInput, options: DaoOptions = {}): Promise<PermissionObjectInteface> => {
        try {
            const getPermissionInput: PermissionGetDaoInput = { id: data.id, paranoid: data.paranoid ?? true };
            return await this.getPermission(getPermissionInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get permission by code
    getPermissionByCode = async (data: PermissionGetByCodeDaoInput, options: DaoOptions = {}): Promise<PermissionObjectInteface> => {
        try {
            const getPermissionInput: PermissionGetDaoInput = { code: data.code, paranoid: data.paranoid ?? true };
            return await this.getPermission(getPermissionInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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

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

    // create a new permission
    create = async (data: PermissionCreateDaoInput, options: DaoOptions = {}): Promise<number> => {
        try {
            const { permissionObj, permissionContentObj, languages } = data;
            const permissionContents: PermissionContentObject[] = LocalizedContent.generate(permissionContentObj, languages) as unknown as PermissionContentObject[];
            const permissionObject: PermissionDataObject = { ...permissionObj, userId: this.userId, permissionContents: permissionContents };
            let permission = await Models.Permission.create(permissionObject, {
                include: [{ model: Models.PermissionContent, as: 'permissionContents' }],
                transaction: options.transaction
            });
            return permission.id;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // update permission
    update = async (data: PermissionUpdateDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            const { id, permissionObj, permissionContentObj, languages } = data;
            await this.storeRevision(id, options);
            await Models.Permission.update({ ...permissionObj, lastUpdatedBy: this.userId }, { where: { id: id }, transaction: options.transaction });
            let verification = await Models.PermissionContent.findOne({ where: { permissionId: id, languageId: languages.requested.id }, transaction: options.transaction });
            if (verification) {
                let permissionContent: PermissionContentObject = { ...permissionContentObj, ...{ languageId: languages.requested.id, permissionId: id } };
                await Models.PermissionContent.update(permissionContent, { where: { id: verification.id }, transaction: options.transaction });
            } else {
                let permissionContent: PermissionContentObject = { ...permissionContentObj, ...{ languageId: languages.requested.id, permissionId: id } };
                await Models.PermissionContent.create(permissionContent, { transaction: options.transaction });
            }
            return;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // delete permission
    delete = async (data: PermissionDeleteDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            const { id } = data;
            const getPermissionByIdInput: PermissionGetByIdDaoInput = { id, paranoid: false };
            let permission = await this.getPermissionById(getPermissionByIdInput, options);
            let code = permission.code + '-' + Moment().toISOString();
            await Models.Permission.update({ updatedBy: this.userId, code: code }, { where: { id: id }, transaction: options.transaction });
            await Models.Permission.destroy({ where: { id: id }, transaction: options.transaction });
            return;
        } catch (err) {
            if (err instanceof AppError) { throw 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:
                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)'));
            } if (specialString) {
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`defaultContent`.`name`,`defaultContent`.`description_text`) AGAINST(:specialString IN BOOLEAN MODE)'));
            }
        }
        if (status != null) {
            where = { ...where, status: status };
        }
        return { where: where, replacements: { alphaString: alphaString, specialString: specialString } };
    };

    // list permission with pagination
    getPermissionList = async (data: PermissionGetPermissionListDaoInput, options: DaoOptions = {}): Promise<PermissionPaginatedData> => {
        try {
            const { categoryId, 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]: [] };
            if (categoryId) {
                where = { ...where, categoryId: categoryId };
            }
            let applyfilter = this.buildFilter(where, searchText, status);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const permissions = await Models.Permission.findAndCountAll({
                attributes: permissionAttributes,
                where: applyfilter.where,
                include: this.includeAssociations(false),
                replacements: applyfilter.replacements,
                offset: offset,
                limit: perPage,
                order: orderBy,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(permissions)) as unknown as PermissionPaginatedData;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // list all permissions
    getAllPermissions = async (data: PermissionGetAllPermissionsDaoInput, options: DaoOptions = {}): Promise<PermissionObjectSummaryInteface[]> => {
        try {
            const { categoryId, listRequest } = data;
            const { searchText, sortBy, sortDirection, status } = listRequest;
            let where: WhereOptions & { [Op.and]: any[] } = { isRevision: false, [Op.and]: [] };
            if (categoryId) {
                where = { ...where, categoryId: categoryId };
            }
            let applyfilter = this.buildFilter(where, searchText, status);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const permissions = await Models.Permission.findAll({
                attributes: permissionAttributes,
                where: applyfilter.where,
                replacements: applyfilter.replacements,
                include: this.includeAssociations(false),
                order: orderBy,
                limit: +process.env.LIST_ALL_LIMIT!,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(permissions)) as unknown as PermissionObjectSummaryInteface[];
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // list permission revisions
    getPermissionRevisionList = async (data: PermissionGetPermissionRevisionListDaoInput, options: DaoOptions = {}): Promise<PermissionPaginatedData> => {
        try {
            const { id, listRequest } = data;
            const { page, perPage, searchText, status, sortBy, sortDirection } = listRequest;
            let offset = (page - 1) * perPage;
            let where: WhereOptions & { [Op.and]: any[] } = { isRevision: true, revisionId: id, [Op.and]: [] };
            let applyfilter = this.buildFilter(where, searchText, status);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const permissions = await Models.Permission.findAndCountAll({
                attributes: permissionAttributes,
                where: applyfilter.where,
                include: this.includeAssociations(false),
                replacements: applyfilter.replacements,
                offset: offset,
                limit: perPage,
                order: orderBy,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(permissions));
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // restore revision for permission
    restoreRevision = async (data: PermissionRestoreRevisionDaoInput, options: DaoOptions = {}): Promise<number> => {
        try {
            const { id } = data;
            const checkPermissionRevisionInput: PermissionDoExistsByIdDaoInput = { id, includeRevision: true };
            if (await this.doExistsById(checkPermissionRevisionInput, options)) {
                let Object: PermissionInterface = await this.getFullObject(id, options);
                if (Object && Object.revisionId) {
                    await this.storeRevision(Object.revisionId, options);
                    let revisonObject = JSON.parse(JSON.stringify(Object));
                    revisonObject = _.omit(revisonObject, ['id', 'createdAt', 'updatedAt', 'deletedAt']);
                    await Models.Permission.update({ lastUpdatedBy: this.userId }, { where: { id: revisonObject.revisionId }, transaction: options.transaction });
                    if (revisonObject.permissionContents && revisonObject.permissionContents.length) {
                        for (let content of revisonObject.permissionContents) {
                            await Models.PermissionContent.upsert({ name: content.name, languageId: content.languageId, permissionId: 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, 'PERMISSION_NOT_FOUND', { id: 'PERMISSION_NOT_FOUND' });
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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

    verifyPermissions = async (data: PermissionVerifyPermissionsDaoInput, options: DaoOptions = {}): Promise<PermissionObjectInteface[]> => {
        try {
            const getPermissionsInput: PermissionGetPermissionsDaoInput = { ids: data.ids, fullObject: false, paranoid: true };
            let permissions: PermissionObjectInteface[] = await this.getPermissions(getPermissionsInput, options);
            return permissions;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }
}
