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

const accountAttributes: AttributeElement[] = [
    'id', 'code', 'name', 'key', 'status', 'createdAt', 'updatedAt'
];

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 AccountDao {
    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: 0,
            }
    ) {
        this.language = options.language;
        this.scope = options.scope ?? [];
        this.config = options.config ?? null;
        this.userId = options.userId ?? null
        this.accountId = options.accountId ?? null
    }

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

    // Generate revision of account prior to update and delete functions.
    private storeRevision = async (data: AccountStoreRevisionDaoInput, options: DaoOptions = {}): Promise<AccountInterface> => {
        try {
            const { id } = data;
            const { transaction } = options;
            const getFullObjectDaoInput: AccountGetFullObjectDaoInput = { id };
            let Object: AccountInterface = await this.getFullObject(getFullObjectDaoInput, { transaction });
            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.accountContents) {
                revisonObject.accountContents[key] = _.omit(revisonObject.accountContents[key], ['id', 'accountId'])
            }
            let revision = await Models.Account.create(revisonObject, { include: [{ model: Models.AccountContent, as: 'accountContents' }], 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[] = [];
        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 account
    getAccount = async (data: AccountGetDaoInput, options: DaoOptions = {}): Promise<AccountObjectInteface> => {
        try {
            const { id = null, code = null, expanded = true, paranoid = true } = data;
            const account = await Models.Account.findOne({
                attributes: accountAttributes,
                where: id ? { id } : code ? { code } : undefined,
                include: this.includeAssociations(expanded),
                paranoid: paranoid,
                transaction: options.transaction
            });
            if (account) {
                return JSON.parse(JSON.stringify(account)) as unknown as AccountObjectInteface;
            } else {
                throw new AppError(404, 'ACCOUNT_NOT_FOUND', { id: 'ACCOUNT_NOT_FOUND', code: 'ACCOUNT_NOT_FOUND' });
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get account by id
    getAccountById = async (data: AccountGetByIdDaoInput, options: DaoOptions = {}): Promise<AccountObjectInteface> => {
        try {
            const getAccountDaoInput: AccountGetDaoInput = { id: data.id, code: null, expanded: data.expanded ?? true, paranoid: data.paranoid ?? true };
            return await this.getAccount(getAccountDaoInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // get account by code
    getAccountByCode = async (data: AccountGetByCodeDaoInput, options: DaoOptions = {}): Promise<AccountObjectInteface> => {
        try {
            const getAccountDaoInput: AccountGetDaoInput = { id: null, code: data.code, expanded: data.expanded ?? true, paranoid: data.paranoid ?? true };
            return await this.getAccount(getAccountDaoInput, options);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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

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

    // create a new account
    create = async (data: AccountCreateDaoInput, options: DaoOptions = {}): Promise<number> => {
        try {
            const { accountObj } = data;
            const { transaction } = options;
            const accountObject: AccountDataObject = { ...accountObj, userId: this.userId };
            let account = await Models.Account.create(accountObject, {
                include: [{ model: Models.AccountContent, as: 'accountContents' }],
                transaction
            });
            return account.id;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // update account
    update = async (data: AccountUpdateDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            const { id, accountObj } = data;
            const { transaction } = options;
            // generate revision for the existing state
            const storeRevisionDaoInput: AccountStoreRevisionDaoInput = { id };
            await this.storeRevision(storeRevisionDaoInput, { transaction });
            await Models.Account.update(accountObj, { where: { id: id }, transaction: transaction });
            return;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // delete account
    delete = async (data: AccountDeleteDaoInput, options: DaoOptions = {}): Promise<void> => {
        try {
            const { id } = data;
            const { transaction } = options;
            const getAccountByIdDaoInput: AccountGetByIdDaoInput = { id, expanded: false };
            let account = await this.getAccountById(getAccountByIdDaoInput, { transaction });
            let code = account.code + '-' + Moment().toISOString();
            await Models.Account.update({ updatedBy: this.userId, code: code }, { where: { id: id }, transaction: transaction });
            await Models.Account.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) => {
        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(`Account`.`name`) AGAINST(:alphaString IN BOOLEAN MODE)'));
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`Account`.`name`) AGAINST(:alphaString IN BOOLEAN MODE)'));
            } if (specialString) {
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`Account`.`name`) AGAINST(:specialString IN BOOLEAN MODE)'));
                (where[Op.and] as any[]).push(Sequelize.literal('MATCH(`Account`.`name`) AGAINST(:specialString IN BOOLEAN MODE)'));
            }
        }
        return { where: where, replacements: { alphaString: alphaString, specialString: specialString } }
    }

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

    // list all accounts
    getAllAccounts = async (data: AccountGetAllListDaoInput, options: DaoOptions = {}): Promise<AccountObjectSummaryInteface[]> => {
        try {
            const { listRequest } = data;
            const { searchText, sortBy, sortDirection } = listRequest
            let alphaString = '';
            let specialString = '';
            let where: WhereOptions & { [Op.and]: any[] } = { isRevision: false, [Op.and]: [] };
            let applyfilter = this.buildFilter(where, searchText);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const accounts = await Models.Account.findAll({
                attributes: accountAttributes,
                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(accounts)) as unknown as AccountObjectSummaryInteface[];
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // list accounts revisions
    getAccountRevisionList = async (data: AccountGetRevisionListDaoInput, options: DaoOptions = {}): Promise<AccountPaginatedData> => {
        try {
            const { id, listRequest } = data;
            const { page, perPage, searchText, 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);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);
            const accounts = await Models.Account.findAndCountAll({
                attributes: accountAttributes,
                where: applyfilter.where,
                include: this.includeAssociations(false),
                replacements: applyfilter.replacements,
                offset: offset,
                limit: perPage,
                order: orderBy,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(accounts)) as unknown as AccountPaginatedData;
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

    // restore revision for account
    restoreRevision = async (data: AccountRestoreRevisionDaoInput, options: DaoOptions = {}): Promise<number> => {
        try {
            const { id } = data;
            const { transaction } = options;
            const doExistsByIdDaoInput: AccountDoExistsByIdDaoInput = { id, includeRevision: true };
            if (await this.doExistsById(doExistsByIdDaoInput, { transaction })) {
                // get full revision Data
                const getFullObjectDaoInput: AccountGetFullObjectDaoInput = { id };
                let Object: AccountInterface = await this.getFullObject(getFullObjectDaoInput, { transaction });
                if (Object && Object.revisionId) {
                    // create new revision from existing state
                    const storeRevisionDaoInput: AccountStoreRevisionDaoInput = { id: Object.revisionId };
                    await this.storeRevision(storeRevisionDaoInput, { transaction });
                    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.Account.update({ lastUpdatedBy: this.userId }, { where: { id: revisonObject.revisionId }, transaction: transaction });
                    // update entity type content
                    if (revisonObject.accountContents && revisonObject.accountContents.length) {
                        for (let content of revisonObject.accountContents) {
                            await Models.AccountContent.upsert({ name: content.name, description: content.description, descriptionText: content.descriptionText, languageId: content.languageId, accountId: 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, 'ACCOUNT_NOT_FOUND', { id: 'ACCOUNT_NOT_FOUND' });
            }
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }

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