import { Sequelize, WhereOptions, FindOptions, literal, fn, col, Op } from "sequelize";
import Models from "../models";
import { AppError } from "../../utils/errors";
import { Common } from "../../utils/common"

const activityAttributes: AttributeElement[] = [
  'id', 'code', 'status', 'createdAt', 'updatedAt',
  [literal('(CASE WHEN `activity->content`.`title` IS NOT NULL THEN `activity->content`.`title` ELSE `activity->defaultContent`.`title` END)'), 'title'],
  [literal('(CASE WHEN `activity->content`.`description` IS NOT NULL THEN `activity->content`.`description` ELSE `activity->defaultContent`.`description` END)'), 'description'],
  [literal('(CASE WHEN `activity->content`.`description_text` IS NOT NULL THEN `activity->content`.`description_text` ELSE `activity->defaultContent`.`description_text` END)'), 'descriptionText']
];
const activityLogAttributes: AttributeElement[] = ['id', 'ip', 'replacements', 'deviceInfo', 'location', '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 = updatedBy.id
              LIMIT 1
            )`),
        'profileImage'
    ]
];

export class ActivityLogDao {
    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
    }


    // get association for the entity
    private includeAssociations = (fullInfo: boolean = false): IncludeOption[] => {
        const includeModels: IncludeOption[] = [
            {
                attributes: [],
                model: Models.ActivityContent,
                as: 'content',
                include: [{ attributes: [], model: Models.Language, as: 'language', where: { code: this.language } }]
            },
            {
                attributes: [],
                model: Models.ActivityContent,
                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" }] }]
                }
            );
        }
        return includeModels;
    }

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

    getActivityLogs = async (data: ActivityLogGetActivityLogsDaoInput, options: DaoOptions = {}): Promise<ActivityLogPaginatedData> => {
        try {
            const { listRequest } = data;
            const { page, perPage, searchText, sortBy, sortDirection, status, userId } = listRequest;
            const offset = (page - 1) * perPage;

            let where: WhereOptions & { [Op.and]: any[] } = {
                accountId: this.accountId,
                userId: userId ? userId : this.userId,
                [Op.and]: []
            };

            let applyfilter = this.buildFilter(where, searchText, status);
            const orderBy = this.buildOrderBy(sortBy, sortDirection);

            const activityLogs = await Models.ActivityLog.findAndCountAll({
                where: applyfilter.where,
                attributes: activityLogAttributes,
                include: [
                    {
                        model: Models.Activity,
                        as: 'activity',
                        attributes: activityAttributes,
                        include: this.includeAssociations(false) // brings in content + defaultContent
                    }
                ],
                replacements: applyfilter.replacements,
                offset,
                limit: perPage,
                order: orderBy,
                transaction: options.transaction
            });
            return JSON.parse(JSON.stringify(activityLogs)) as unknown as ActivityLogPaginatedData;
        } catch (err) {
            if (err instanceof AppError) throw err;
            throw new AppError(500, 'SOMETHING_WENT_WRONG_WITH_DAO', err);
        }
    }


}
