import { Sequelize, WhereOptions, FindOptions, literal, fn, col, Transaction, 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 faqAttributes: AttributeElement[] = [
    'id', 'code', 'status', 'createdAt', 'updatedAt',
    [literal('(case when `content`.question is not null then `content`.question else `defaultContent`.question END)'), 'question'],
    [literal('(case when `content`.answer is not null then `content`.answer else `defaultContent`.answer END)'), 'answer'],
    [literal('(case when `content`.answer_text is not null then `content`.answer_text else `defaultContent`.answer_text END)'), 'answerText']
];

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 faqCategoryAttributes: AttributeElement[] = [
    'id', 'code', [literal('(case when `faqCategory->content`.name is not null then `faqCategory->content`.name else `faqCategory->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 FaqDao {
    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 faq sortOrder
    setSortOrder = async (data: FaqSetSortOrderDaoInput, options: DaoOptions = {}): Promise<boolean> => {
        const { id, before = null, after = null } = data;
        const { transaction } = options;
        try {
            let faqData = await Models.Faq.findOne({ attributes: ['id', 'sortOrder'], where: { id: id, accountId: this.accountId, isRevision: false } });
            if (faqData) {
                if (before || after) {
                    let locationData = await Models.Faq.findOne({ attributes: ['id', 'sortOrder'], where: { id: before ? before : after, accountId: this.accountId, isRevision: false } });
                    if (!locationData) {
                        return false;
                    }
                    if (faqData.sortOrder < locationData.sortOrder) {
                        await Models.Faq.decrement('sortOrder', {
                            by: 1,
                            where: {
                                accountId: this.accountId,
                                [Op.and]: [
                                    { sortOrder: { [Op.gt]: faqData.sortOrder } },
                                    before ? { sortOrder: { [Op.lt]: locationData.sortOrder } } : { sortOrder: { [Op.lte]: locationData.sortOrder } }
                                ]
                            },
                            transaction: transaction
                        });
                        await Models.Faq.update(before ? { sortOrder: locationData.sortOrder - 1 } : { sortOrder: locationData.sortOrder }, { where: { id: faqData.id, accountId: this.accountId }, transaction: transaction });
                    } else if (faqData.sortOrder > locationData.sortOrder) {
                        await Models.Faq.increment('sortOrder', {
                            by: 1,
                            where: {
                                accountId: this.accountId,
                                [Op.and]: [
                                    before ? { sortOrder: { [Op.gte]: locationData.sortOrder } } : { sortOrder: { [Op.gt]: locationData.sortOrder } },
                                    { sortOrder: { [Op.lt]: faqData.sortOrder } }
                                ]
                            },
                            transaction: transaction
                        });
                        await Models.Faq.update(before ? { sortOrder: locationData.sortOrder } : { sortOrder: locationData.sortOrder + 1 }, { where: { id: faqData.id, accountId: this.accountId }, transaction: transaction });
                    }
                }
                else {
                    let maxSortOrder = await Models.Faq.max('sortOrder', { where: { accountId: this.accountId } });
                    await Models.Faq.update(
                        { sortOrder: (maxSortOrder || 0) + 1 }, // default to 1 if no max found
                        { where: { id: faqData.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 faq object
    private getFullObject = async (id: number, options: DaoOptions = {}): Promise<FaqInterface> => {
        try {
            let Faq = await Models.Faq.findOne({
                where: { id: id, accountId: this.accountId },
                include: [{ model: Models.FaqContent, as: 'faqContents' }],
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(Faq))
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'ERROR_WHILE_GETTING_FULL_DATA', err);
        }
    }

    // Generate revision of faq prior to update and delete functions.
    private storeRevision = async (id: number, options: DaoOptions = {}): Promise<FaqInterface> => {
        try {
            let Object: FaqInterface = 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.faqContents) {
                revisonObject.faqContents[key] = _.omit(revisonObject.faqContents[key], ['id', 'faqId'])
            }
            let revision = await Models.Faq.create(revisonObject, { include: [{ model: Models.FaqContent, as: 'faqContents' }], 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.FaqContent,
                as: 'content',
                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: this.language } }]
            },
            {
                attributes: [],
                model: Models.FaqContent,
                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: faqCategoryAttributes,
                    model: Models.Category,
                    as: 'faqCategory',
                    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 faq
    getFaq = async (data: FaqGetDaoInput, options: DaoOptions = {}): Promise<faqObjectInteface> => {
        try {
            const { id = null, code = null, paranoid = false } = data;
            const faq = await Models.Faq.findOne({
                attributes: faqAttributes,
                where: { ...(id ? { id } : code ? { code } : {}), accountId: this.accountId },
                include: this.includeAssociations(true),
                paranoid: paranoid,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(faq)) as unknown as faqObjectInteface;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get faq by id
    getFaqById = async (data: FaqGetByIdDaoInput, options: DaoOptions = {}): Promise<faqObjectInteface> => {
        try {
            const getFaqInput: FaqGetDaoInput = { id: data.id, code: null, paranoid: data.paranoid ?? true };
            return await this.getFaq(getFaqInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get faq by code
    getFaqByCode = async (data: FaqGetByCodeDaoInput, options: DaoOptions = {}): Promise<faqObjectInteface> => {
        try {
            const getFaqInput: FaqGetDaoInput = { id: null, code: data.code, paranoid: data.paranoid ?? true };
            return await this.getFaq(getFaqInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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

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

    // create a new faq
    create = async (data: FaqCreateDaoInput, options: DaoOptions = {}): Promise<number> => {
        try {
            const { faqObj, faqContentObj, languages } = data;
            const faqContents: faqContentObject[] = LocalizedContent.generate(faqContentObj, languages) as unknown as faqContentObject[];
            const faqObject: faqDataObject = { ...faqObj, userId: this.userId, accountId: this.accountId, faqContents: faqContents };
            let faq = await Models.Faq.create(faqObject, {
                include: [{ model: Models.FaqContent, as: 'faqContents' }],
                transaction: options.transaction
            });
            return faq.id;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // update faq
    update = async (data: FaqUpdateDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            const { id, faqObj, faqContentObj, languages } = data;
            // generate revision for the existing state
            await this.storeRevision(id, options);
            await Models.Faq.update({ ...faqObj, lastUpdatedBy: this.userId }, { where: { id: id }, transaction: options.transaction });
            // check if content exists in requested language
            let verification = await Models.FaqContent.findOne({ where: { faqId: id, languageId: languages.requested.id }, transaction: options.transaction });
            if (verification) { // update if content exists in the requested language
                let faqContent: faqContentObject = { ...faqContentObj, ...{ languageId: languages.requested.id, faqId: id } }
                await Models.FaqContent.update(faqContent, { where: { id: verification.id }, transaction: options.transaction });

            } else { // create if content does not exists in the requested language
                let faqContent: faqContentObject = { ...faqContentObj, ...{ languageId: languages.requested.id, faqId: id } }
                await Models.FaqContent.create(faqContent, { transaction: options.transaction });
            }
            return;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // delete faq
    delete = async (data: FaqDeleteDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            const { id } = data;
            const getFaqByIdInput: FaqGetByIdDaoInput = { id, paranoid: false };
            let faq = await this.getFaqById(getFaqByIdInput, options);
            let code = faq.code + '-' + Moment().toISOString();
            await Models.Faq.update({ updatedBy: this.userId, code: code }, { where: { id: id }, transaction: options.transaction });
            await Models.Faq.destroy({ where: { id: 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);
        }
    }

    // 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`.`question`,`defaultContent`.`answer_text`) AGAINST(:alphaString IN BOOLEAN MODE)'));
            } if (specialString) {
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`defaultContent`.`question`,`defaultContent`.`answer_text`) AGAINST(:specialString IN BOOLEAN MODE)'));
            }
        }
        if (status != null) {
            where = { ...where, status: status }
        }
        return { where: where, replacements: { alphaString: alphaString, specialString: specialString } }
    }

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

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

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

    // restore revision for faq
    restoreRevision = async (data: FaqRestoreRevisionDaoInput, options: DaoOptions = {}): Promise<number> => {
        try {
            const { id } = data;
            const checkFaqRevisionInput: FaqDoExistsByIdDaoInput = { id, includeRevision: true };
            if (await this.doExistsById(checkFaqRevisionInput, options)) {
                // get full revision Data
                let Object: FaqInterface = 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.Faq.update({ lastUpdatedBy: this.userId }, { where: { id: revisonObject.revisionId }, transaction: options.transaction });
                    // update entity type content
                    if (revisonObject.faqContents && revisonObject.faqContents.length) {
                        for (let content of revisonObject.faqContents) {
                            await Models.FaqContent.upsert({ name: content.name, languageId: content.languageId, faqId: 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, 'FAQ_NOT_FOUND', { id: 'FAQ_NOT_FOUND' });
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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