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 emailTemplateAttributes: AttributeElement[] = [
    'id', 'code', 'replacements', 'status', 'createdAt', 'updatedAt',
    [literal('(case when `content`.title is not null then `content`.title else `defaultContent`.subject END)'), 'title'],
    [literal('(case when `content`.subject is not null then `content`.subject else `defaultContent`.subject END)'), 'subject'],
    [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 emailTemplateAttachmentAttributes: AttributeElement[] = [
    'id',
    'fileName',
    'uniqueName',
    [fn('CONCAT', process.env.PROTOCOL, '://', process.env.API_HOST, "/attachment/", literal('`emailTemplateAttachments`.`unique_name`')), 'filePath'],
    [fn('CONCAT', process.env.CDN_PATH, literal('`emailTemplateAttachments`.`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 EmailTemplateDao {
    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 emailTemplate sortOrder
    setSortOrder = async (data: EmailTemplateSetSortOrderDaoInput, options: DaoOptions = {}): Promise<boolean> => {
        const { id, before = null, after = null } = data;
        const { transaction } = options;
        try {
            let emailTemplateData = await Models.EmailTemplate.findOne({ attributes: ['id', 'sortOrder'], where: { id: id, isRevision: false } });
            if (emailTemplateData) {
                if (before || after) {
                    let locationData = await Models.EmailTemplate.findOne({ attributes: ['id', 'sortOrder'], where: { id: before ? before : after, isRevision: false } });
                    if (!locationData) {
                        return false;
                    }
                    if (emailTemplateData.sortOrder < locationData.sortOrder) {
                        await Models.EmailTemplate.decrement('sortOrder', {
                            by: 1,
                            where: {
                                [Op.and]: [
                                    { sortOrder: { [Op.gt]: emailTemplateData.sortOrder } },
                                    before ? { sortOrder: { [Op.lt]: locationData.sortOrder } } : { sortOrder: { [Op.lte]: locationData.sortOrder } }
                                ]
                            },
                            transaction: transaction
                        });
                        await Models.EmailTemplate.update(before ? { sortOrder: locationData.sortOrder - 1 } : { sortOrder: locationData.sortOrder }, { where: { id: emailTemplateData.id }, transaction: transaction });
                    } else if (emailTemplateData.sortOrder > locationData.sortOrder) {
                        await Models.EmailTemplate.increment('sortOrder', {
                            by: 1,
                            where: {
                                [Op.and]: [
                                    before ? { sortOrder: { [Op.gte]: locationData.sortOrder } } : { sortOrder: { [Op.gt]: locationData.sortOrder } },
                                    { sortOrder: { [Op.lt]: emailTemplateData.sortOrder } }
                                ]
                            },
                            transaction: transaction
                        });
                        await Models.EmailTemplate.update(before ? { sortOrder: locationData.sortOrder } : { sortOrder: locationData.sortOrder + 1 }, { where: { id: emailTemplateData.id }, transaction: transaction });
                    }
                }
                else {
                    let maxSortOrder = await Models.EmailTemplate.max('sortOrder');
                    await Models.EmailTemplate.update(
                        { sortOrder: (maxSortOrder || 0) + 1 }, // default to 1 if no max found
                        { where: { id: emailTemplateData.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 email template object
    private getFullObject = async (data: EmailTemplateGetFullObjectDaoInput, options: DaoOptions = {}): Promise<EmailTemplateInterface> => {
        const { id } = data;
        const { transaction } = options;
        try {
            let EmailTemplate = await Models.EmailTemplate.findOne({
                where: { id: id },
                include: [{ model: Models.EmailTemplateContent, as: 'emailTemplateContents' }],
                transaction
            });
            return JSON.parse(JSON.stringify(EmailTemplate))
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'ERROR_WHILE_GETTING_FULL_DATA', err);
        }
    }

    // Generate revision of Email Template prior to update and delete functions.
    private storeRevision = async (data: EmailTemplateStoreRevisionDaoInput, options: DaoOptions = {}): Promise<EmailTemplateInterface> => {
        const { id } = data;
        const { transaction } = options;
        try {
            const getFullObjectInput: EmailTemplateGetFullObjectDaoInput = { id };
            let Object: EmailTemplateInterface = await this.getFullObject(getFullObjectInput, 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.emailTemplateContents) {
                revisonObject.emailTemplateContents[key] = _.omit(revisonObject.emailTemplateContents[key], ['id', 'emailTemplateId'])
            }
            let revision = await Models.EmailTemplate.create(revisonObject, { include: [{ model: Models.EmailTemplateContent, as: 'emailTemplateContents' }], transaction: 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.EmailTemplateContent,
                as: 'content',
                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: this.language } }]
            },
            {
                attributes: [],
                model: Models.EmailTemplateContent,
                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: emailTemplateAttachmentAttributes,
                    model: Models.Attachment,
                    as: 'emailTemplateAttachments',
                    through: { attributes: [] }
                }
            );
        }
        return includeModels;
    }

    // get emailTemplate
    getEmailTemplate = async (data: EmailTemplateGetDaoInput, options: DaoOptions = {}): Promise<EmailTemplateObjectInteface> => {
        const { id = null, code = null, expanded = true, paranoid = true } = data;
        const { transaction } = options;
        try {
            const emailTemplate = await Models.EmailTemplate.findOne({
                attributes: emailTemplateAttributes,
                where: id ? { id } : code ? { code } : undefined,
                include: this.includeAssociations(expanded),
                paranoid: paranoid,
                subQuery: false,
                transaction
            });
            if (emailTemplate) {
                return JSON.parse(JSON.stringify(emailTemplate)) as unknown as EmailTemplateObjectInteface;
            } else {
                throw new AppError(404, 'EMAIL_TEMPLATE_NOT_FOUND', { id: 'EMAIL_TEMPLATE_NOT_FOUND', code: 'EMAIL_TEMPLATE_NOT_FOUND' });
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get emailTemplate by id
    getEmailTemplateById = async (data: EmailTemplateGetByIdDaoInput, options: DaoOptions = {}): Promise<EmailTemplateObjectInteface> => {
        const { id, expanded = true, paranoid = true } = data;
        try {
            const getEmailTemplateInput: EmailTemplateGetDaoInput = { id, expanded, paranoid };
            return await this.getEmailTemplate(getEmailTemplateInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get email Template by code
    getEmailTemplateByCode = async (data: EmailTemplateGetByCodeDaoInput, options: DaoOptions = {}): Promise<EmailTemplateObjectInteface> => {
        const { code, expanded = true, paranoid = true } = data;
        try {
            const getEmailTemplateInput: EmailTemplateGetDaoInput = { code, expanded, paranoid };
            return await this.getEmailTemplate(getEmailTemplateInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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

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

    // create a new Email Template
    create = async (data: EmailTemplateCreateDaoInput, options: DaoOptions = {}): Promise<number> => {
        const { emailTemplateObj, emailTemplateContentObj, emailTemplateAttachments, languages } = data;
        const { transaction } = options;
        try {
            const emailTemplateContents: EmailTemplateContentObject[] = LocalizedContent.generate(emailTemplateContentObj, languages) as unknown as EmailTemplateContentObject[];
            const emailTemplateObject: EmailTemplateDataObject = { ...emailTemplateObj, userId: this.userId, accountId: this.accountId, emailTemplateContents: emailTemplateContents };
            let emailTemplate = await Models.EmailTemplate.create(emailTemplateObject, {
                include: [{ model: Models.EmailTemplateContent, as: 'emailTemplateContents' }],
                transaction
            });
            if (emailTemplateAttachments) {
                await emailTemplate.setEmailTemplateAttachments(emailTemplateAttachments, { transaction: transaction })
            }
            return emailTemplate.id;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // update email template
    update = async (data: EmailTemplateUpdateDaoInput, options: DaoOptions = {}): Promise<void> => {
        const { id, emailTemplateObj, emailTemplateContentObj, emailTemplateAttachments, languages } = data;
        const { transaction } = options;
        try {
            // generate revision for the existing state
            const storeRevisionInput: EmailTemplateStoreRevisionDaoInput = { id };
            await this.storeRevision(storeRevisionInput, options);
            await Models.EmailTemplate.update({ ...emailTemplateObj, lastUpdatedBy: this.userId }, { where: { id: id }, transaction: transaction })
            // check if content exists in requested language
            let verification = await Models.EmailTemplateContent.findOne({ where: { emailTemplateId: id, languageId: languages.requested.id } });
            if (verification) { // update if content exists in the requested language

                let emailTemplateContent: EmailTemplateContentObject = { ...emailTemplateContentObj, ...{ languageId: languages.requested.id, emailTemplateId: id } }
                await Models.EmailTemplateContent.update(emailTemplateContent, { where: { id: verification.id }, transaction: transaction })

            } else { // create if content does not exists in the requested language
                let emailTemplateContent: EmailTemplateContentObject = { ...emailTemplateContentObj, ...{ languageId: languages.requested.id, emailTemplateId: id } }
                await Models.EmailTemplateContent.create(emailTemplateContent, { transaction: transaction })
            }
            let template = Models.EmailTemplate.build({ id: id }, { isNewRecord: false });
            if (emailTemplateAttachments) {
                await template.setEmailTemplateAttachments(emailTemplateAttachments, { transaction: transaction })
            } else {
                await template.setEmailTemplateAttachments([], { transaction: transaction })
            }
            return;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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

    // list Email Templates with pagination
    getEmailTemplateList = async (data: EmailTemplateGetListDaoInput, options: DaoOptions = {}): Promise<EmailTemplatePaginatedData> => {
        const { listRequest } = data;
        const { transaction } = options;
        try {
            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 emailTemplates = await Models.EmailTemplate.findAndCountAll({
                attributes: emailTemplateAttributes,
                where: applyfilter.where,
                include: this.includeAssociations(false),
                replacements: applyfilter.replacements,
                offset: offset,
                limit: perPage,
                order: orderBy,
                transaction
            });
            return JSON.parse(JSON.stringify(emailTemplates)) as unknown as EmailTemplatePaginatedData;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // list all Email Templates
    getAllEmailTemplates = async (data: EmailTemplateGetAllListDaoInput, options: DaoOptions = {}): Promise<EmailTemplateObjectInteface[] | EmailTemplateObjectSummaryInteface[]> => {
        const { listRequest } = data;
        const { transaction } = options;
        try {
            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 emailTemplates = await Models.EmailTemplate.findAll({
                attributes: emailTemplateAttributes,
                where: applyfilter.where,
                replacements: applyfilter.replacements,
                include: this.includeAssociations(false),
                order: orderBy,
                limit: +process.env.LIST_ALL_LIMIT!,
                transaction
            });
            return JSON.parse(JSON.stringify(emailTemplates)) as unknown as EmailTemplateObjectInteface[] | EmailTemplateObjectSummaryInteface[];
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // list EmailTemplate revisions
    getEmailTemplateRevisionList = async (data: EmailTemplateGetRevisionListDaoInput, options: DaoOptions = {}): Promise<EmailTemplatePaginatedData> => {
        const { id, listRequest } = data;
        const { transaction } = options;
        try {
            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 emailTemplates = await Models.EmailTemplate.findAndCountAll({
                attributes: emailTemplateAttributes,
                where: applyfilter.where,
                include: this.includeAssociations(false),
                replacements: applyfilter.replacements,
                offset: offset,
                limit: perPage,
                order: orderBy,
                transaction
            });
            return JSON.parse(JSON.stringify(emailTemplates)) as unknown as EmailTemplatePaginatedData;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // restore EmailTemplate revision 
    restoreRevision = async (data: EmailTemplateRestoreRevisionDaoInput, options: DaoOptions = {}): Promise<number> => {
        const { id } = data;
        const { transaction } = options;
        try {
            const doExistsByIdInput: EmailTemplateDoExistsByIdDaoInput = { id, includeRevision: true };
            if (await this.doExistsById(doExistsByIdInput, options)) {
                // get full revision Data
                const getFullObjectInput: EmailTemplateGetFullObjectDaoInput = { id };
                let Object: EmailTemplateInterface = await this.getFullObject(getFullObjectInput, options);
                if (Object && Object.revisionId) {
                    // create new revision from existing state
                    const storeRevisionInput: EmailTemplateStoreRevisionDaoInput = { id: Object.revisionId };
                    await this.storeRevision(storeRevisionInput, 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.EmailTemplate.update({ lastUpdatedBy: this.userId }, { where: { id: revisonObject.revisionId }, transaction: transaction });
                    // update entity type content
                    if (revisonObject.emailTemplateContents && revisonObject.emailTemplateContents.length) {
                        for (let content of revisonObject.emailTemplateContents) {
                            await Models.EmailTemplateContent.upsert({ title: content.title, subject: content.subject, body: content.body, bodyText: content.bodyText, languageId: content.languageId, emailTemplateId: Object.revisionId }, { transaction: 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, 'EMAIL_TEMPLATE_NOT_FOUND', { id: 'EMAIL_TEMPLATE_NOT_FOUND' });
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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

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