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 notificationAttributes: AttributeElement[] = [
    'id', 'code', 'replacements', 'status', 'createdAt', 'updatedAt',
    [literal('(case when `content`.title is not null then `content`.title  else `defaultContent`.title END)'), 'title'],
    [literal('(case when `content`.body is not null then `content`.body else `defaultContent`.body END)'), 'body'],
    [literal('(case when `content`.body_text is not null then `content`.body_text else `defaultContent`.body_text END)'), 'bodyText']
];

const notificationImage: AttributeElement[] = [
    'id',
    'fileName',
    'uniqueName',
    [fn('CONCAT', process.env.PROTOCOL, '://', process.env.API_HOST, "/attachment/", literal('`notificationImage`.`unique_name`')), 'filePath'],
    [fn('CONCAT', process.env.CDN_PATH, literal('`notificationImage`.`file_path`')), 'cdnUrl'],
]

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 NotificationDao {
    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 notification sortOrder
    setSortOrder = async (data: NotificationSetSortOrderDaoInput, options: DaoOptions = {}): Promise<boolean> => {
        const { id, before = null, after = null } = data;
        const { transaction } = options;
        try {
            let notificationData = await Models.Notification.findOne({ attributes: ['id', 'sortOrder'], where: { id: id, isRevision: false }, transaction });
            if (notificationData) {
                if (before || after) {
                    let locationData = await Models.Notification.findOne({ attributes: ['id', 'sortOrder'], where: { id: before ? before : after, isRevision: false }, transaction });
                    if (!locationData) {
                        return false;
                    }
                    if (notificationData.sortOrder < locationData.sortOrder) {
                        await Models.Notification.decrement('sortOrder', {
                            by: 1,
                            where: {
                                [Op.and]: [
                                    { sortOrder: { [Op.gt]: notificationData.sortOrder } },
                                    before ? { sortOrder: { [Op.lt]: locationData.sortOrder } } : { sortOrder: { [Op.lte]: locationData.sortOrder } }
                                ]
                            },
                            transaction: transaction
                        });
                        await Models.Notification.update(before ? { sortOrder: locationData.sortOrder - 1 } : { sortOrder: locationData.sortOrder }, { where: { id: notificationData.id }, transaction: transaction });
                    } else if (notificationData.sortOrder > locationData.sortOrder) {
                        await Models.Notification.increment('sortOrder', {
                            by: 1,
                            where: {
                                [Op.and]: [
                                    before ? { sortOrder: { [Op.gte]: locationData.sortOrder } } : { sortOrder: { [Op.gt]: locationData.sortOrder } },
                                    { sortOrder: { [Op.lt]: notificationData.sortOrder } }
                                ]
                            },
                            transaction: transaction
                        });
                        await Models.Notification.update(before ? { sortOrder: locationData.sortOrder } : { sortOrder: locationData.sortOrder + 1 }, { where: { id: notificationData.id }, transaction: transaction });
                    }
                }
                else {
                    let maxSortOrder = await Models.Notification.max('sortOrder');
                    await Models.Notification.update(
                        { sortOrder: (maxSortOrder || 0) + 1 }, // default to 1 if no max found
                        { where: { id: notificationData.id }, 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 notification template object
    private getFullObject = async (id: number, options: DaoOptions = {}): Promise<NotificationInterface> => {
        try {
            let Notification = await Models.Notification.findOne({
                where: { id: id },
                include: [{ model: Models.NotificationContent, as: 'notificationContents' }],
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(Notification))
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'ERROR_WHILE_GETTING_FULL_DATA', err);
        }
    }

    // Generate revision of Notification Template prior to update and delete functions.
    private storeRevision = async (id: number, options: DaoOptions = {}): Promise<NotificationInterface> => {
        try {
            let Object: NotificationInterface = 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.notificationContents) {
                revisonObject.notificationContents[key] = _.omit(revisonObject.notificationContents[key], ['id', 'notificationId'])
            }
            let revision = await Models.Notification.create(revisonObject, { include: [{ model: Models.NotificationContent, as: 'notificationContents' }], 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.NotificationContent,
                as: 'content',
                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: this.language } }]
            },
            {
                attributes: [],
                model: Models.NotificationContent,
                as: 'defaultContent',
                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: process.env.DEFAULT_LANGUAGE_CODE } }]
            },
            {
                attributes: notificationImage,
                model: Models.Attachment,
                as: 'notificationImage',
            }
        ];
        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 notification
    getNotification = async (data: NotificationGetDaoInput, options: DaoOptions = {}): Promise<NotificationObjectInteface> => {
        try {
            const { id = null, code = null, expanded = true, paranoid = true } = data;
            const notification = await Models.Notification.findOne({
                attributes: notificationAttributes,
                where: id ? { id } : code ? { code } : undefined,
                include: this.includeAssociations(expanded),
                paranoid: paranoid,
                subQuery: false,
                transaction: options.transaction
            });
            if (notification) {
                return JSON.parse(JSON.stringify(notification)) as unknown as NotificationObjectInteface;
            } else {
                throw new AppError(404, 'NOTIFICATION_NOT_FOUND', { id: 'NOTIFICATION_NOT_FOUND', code: 'NOTIFICATION_NOT_FOUND' });
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get notification by id
    getNotificationById = async (data: NotificationGetByIdDaoInput, options: DaoOptions = {}): Promise<NotificationObjectInteface> => {
        try {
            const getNotificationInput: NotificationGetDaoInput = {
                id: data.id,
                code: null,
                expanded: data.expanded ?? true,
                paranoid: data.paranoid ?? true,
            };
            return await this.getNotification(getNotificationInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get notification Template by code
    getNotificationByCode = async (data: NotificationGetByCodeDaoInput, options: DaoOptions = {}): Promise<NotificationObjectInteface> => {
        try {
            const getNotificationInput: NotificationGetDaoInput = {
                id: null,
                code: data.code,
                expanded: data.expanded ?? true,
                paranoid: data.paranoid ?? true,
            };
            return await this.getNotification(getNotificationInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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

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

    // create a new Notification Template
    create = async (data: NotificationCreateDaoInput, options: DaoOptions = {}): Promise<number> => {
        try {
            const { notificationObj, notificationContentObj, languages } = data;
            const notificationContents: NotificationContentObject[] = LocalizedContent.generate(notificationContentObj, languages) as unknown as NotificationContentObject[];
            const notificationObject: NotificationDataObject = { ...notificationObj, userId: this.userId, accountId: this.accountId, notificationContents: notificationContents };
            let notification = await Models.Notification.create(notificationObject, {
                include: [{ model: Models.NotificationContent, as: 'notificationContents' }],
                transaction: options.transaction
            });
            return notification.id;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // update notification template
    update = async (data: NotificationUpdateDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            const { id, notificationObj, notificationContentObj, languages } = data;
            // generate revision for the existing state
            await this.storeRevision(id, options);
            await Models.Notification.update({ ...notificationObj, lastUpdatedBy: this.userId }, { where: { id: id }, transaction: options.transaction })
            // check if content exists in requested language
            let verification = await Models.NotificationContent.findOne({ where: { notificationId: id, languageId: languages.requested.id }, transaction: options.transaction });
            if (verification) { // update if content exists in the requested language

                let notificationContent: NotificationContentObject = { ...notificationContentObj, ...{ languageId: languages.requested.id, notificationId: id } }
                await Models.NotificationContent.update(notificationContent, { where: { id: verification.id }, transaction: options.transaction })

            } else { // create if content does not exists in the requested language
                let notificationContent: NotificationContentObject = { ...notificationContentObj, ...{ languageId: languages.requested.id, notificationId: id } }
                await Models.NotificationContent.create(notificationContent, { transaction: options.transaction })
            }
            return;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // delete notification template
    delete = async (data: NotificationDeleteDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            const { id } = data;
            const getNotificationByIdInput: NotificationGetByIdDaoInput = { id, expanded: false };
            let notification = await this.getNotificationById(getNotificationByIdInput, options);
            let code = notification.code + '-' + Moment().toISOString();
            await Models.Notification.update({ updatedBy: this.userId, code: code }, { where: { id: id }, transaction: options.transaction });
            await Models.Notification.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:
                // 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`.`title`,`defaultContent`.`body_text`) AGAINST(:alphaString IN BOOLEAN MODE)'));
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`content`.`title`,`content`.`body_text`) AGAINST(:alphaString IN BOOLEAN MODE)'));
            } if (specialString) {
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`defaultContent`.`title`,`defaultContent`.`body_text`) AGAINST(:specialString IN BOOLEAN MODE)'));
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`content`.`title`,`content`.`body_text`) AGAINST(:specialString IN BOOLEAN MODE)'));
            }
        }
        if (status != null) {
            where = { ...where, status: status }
        }
        return { where: where, replacements: { alphaString: alphaString, specialString: specialString } }
    }

    // list Notification Templates with pagination
    getNotificationList = async (data: NotificationGetListDaoInput, options: DaoOptions = {}): Promise<NotificationPaginatedData> => {
        try {
            const { listRequest } = data;
            const { page, perPage, searchText, status, sortBy, sortDirection } = listRequest;
            let offset = (page - 1) * perPage;
            let where: WhereOptions & { [Op.and]: any[] } = { isRevision: false, [Op.and]: [] };
            let applyfilter = this.buildFilter(where, searchText, status);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const notifications = await Models.Notification.findAndCountAll({
                attributes: notificationAttributes,
                where: applyfilter.where,
                include: this.includeAssociations(false),
                replacements: applyfilter.replacements,
                offset: offset,
                limit: perPage,
                order: orderBy,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(notifications)) as unknown as NotificationPaginatedData;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // list all Notification Templates
    getAllNotifications = async (data: NotificationGetAllDaoInput, options: DaoOptions = {}): Promise<NotificationObjectInteface[] | NotificationObjectSummaryInteface[]> => {
        try {
            const { listRequest } = data;
            const { searchText, status, sortBy, sortDirection } = listRequest;
            let where: WhereOptions & { [Op.and]: any[] } = { isRevision: false, [Op.and]: [] };
            let applyfilter = this.buildFilter(where, searchText, status);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const notifications = await Models.Notification.findAll({
                attributes: notificationAttributes,
                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(notifications)) as unknown as NotificationObjectInteface[] | NotificationObjectSummaryInteface[];
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // list Notification revisions
    getNotificationRevisionList = async (data: NotificationGetRevisionListDaoInput, options: DaoOptions = {}): Promise<NotificationPaginatedData> => {
        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 notifications = await Models.Notification.findAndCountAll({
                attributes: notificationAttributes,
                where: applyfilter.where,
                include: this.includeAssociations(false),
                replacements: applyfilter.replacements,
                offset: offset,
                limit: perPage,
                order: orderBy,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(notifications)) as unknown as NotificationPaginatedData;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // restore Notification revision 
    restoreRevision = async (data: NotificationRestoreRevisionDaoInput, options: DaoOptions = {}): Promise<number> => {
        try {
            const { id } = data;
            const checkNotificationRevisionInput: NotificationDoExistsByIdDaoInput = { id, includeRevision: true };
            if (await this.doExistsById(checkNotificationRevisionInput, options)) {
                // get full revision Data
                let Object: NotificationInterface = 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.Notification.update({ lastUpdatedBy: this.userId }, { where: { id: revisonObject.revisionId }, transaction: options.transaction });
                    // update entity type content
                    if (revisonObject.notificationContents && revisonObject.notificationContents.length) {
                        for (let content of revisonObject.notificationContents) {
                            await Models.NotificationContent.upsert({ title: content.title, body: content.body, bodyText: content.bodyText, languageId: content.languageId, notificationId: 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, 'NOTIFICATION_NOT_FOUND', { id: 'NOTIFICATION_NOT_FOUND' });
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get Notification id from Notification code
    getIdFromCode = async (data: NotificationGetIdFromCodeDaoInput, options: DaoOptions = {}): Promise<number> => {
        try {
            let notification = await Models.Notification.findOne({ attributes: ['id'], where: { code: data.code }, transaction: options.transaction });
            if (notification) {
                return notification.id;
            } else {
                throw new AppError(404, 'NOTIFICATION_NOT_FOUND', { code: 'NOTIFICATION_NOT_FOUND' });
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // update notification template status
    updateStatus = async (data: NotificationUpdateStatusDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            await Models.Notification.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);
        }
    }
}
