
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Insight_snapshotsDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const insight_snapshots = await db.insight_snapshots.create(
            {
                id: data.id || undefined,
        
        content_type: data.content_type
        ||
        null
            ,
            
        content_ref: data.content_ref
        ||
        null
            ,
            
        window_start_at: data.window_start_at
        ||
        null
            ,
            
        window_end_at: data.window_end_at
        ||
        null
            ,
            
        impressions: data.impressions
        ||
        null
            ,
            
        reach: data.reach
        ||
        null
            ,
            
        profile_visits: data.profile_visits
        ||
        null
            ,
            
        likes: data.likes
        ||
        null
            ,
            
        comments: data.comments
        ||
        null
            ,
            
        saves: data.saves
        ||
        null
            ,
            
        shares: data.shares
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await insight_snapshots.setOwner( data.owner || null, {
            transaction,
        });
        

        

        

        return insight_snapshots;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const insight_snapshotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                content_type: item.content_type
            ||
            null
            ,
            
                content_ref: item.content_ref
            ||
            null
            ,
            
                window_start_at: item.window_start_at
            ||
            null
            ,
            
                window_end_at: item.window_end_at
            ||
            null
            ,
            
                impressions: item.impressions
            ||
            null
            ,
            
                reach: item.reach
            ||
            null
            ,
            
                profile_visits: item.profile_visits
            ||
            null
            ,
            
                likes: item.likes
            ||
            null
            ,
            
                comments: item.comments
            ||
            null
            ,
            
                saves: item.saves
            ||
            null
            ,
            
                shares: item.shares
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const insight_snapshots = await db.insight_snapshots.bulkCreate(insight_snapshotsData, { transaction });

        // For each item created, replace relation files
        

        return insight_snapshots;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const insight_snapshots = await db.insight_snapshots.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.content_ref !== undefined) updatePayload.content_ref = data.content_ref;
        
        
        if (data.window_start_at !== undefined) updatePayload.window_start_at = data.window_start_at;
        
        
        if (data.window_end_at !== undefined) updatePayload.window_end_at = data.window_end_at;
        
        
        if (data.impressions !== undefined) updatePayload.impressions = data.impressions;
        
        
        if (data.reach !== undefined) updatePayload.reach = data.reach;
        
        
        if (data.profile_visits !== undefined) updatePayload.profile_visits = data.profile_visits;
        
        
        if (data.likes !== undefined) updatePayload.likes = data.likes;
        
        
        if (data.comments !== undefined) updatePayload.comments = data.comments;
        
        
        if (data.saves !== undefined) updatePayload.saves = data.saves;
        
        
        if (data.shares !== undefined) updatePayload.shares = data.shares;
        
        
        updatePayload.updatedById = currentUser.id;

        await insight_snapshots.update(updatePayload, {transaction});

        
        
        if (data.owner !== undefined) {
            await insight_snapshots.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        

        
        

        

        return insight_snapshots;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const insight_snapshots = await db.insight_snapshots.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of insight_snapshots) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of insight_snapshots) {
                await record.destroy({transaction});
            }
        });


        return insight_snapshots;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const insight_snapshots = await db.insight_snapshots.findByPk(id, options);

        await insight_snapshots.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await insight_snapshots.destroy({
            transaction
        });

        return insight_snapshots;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const insight_snapshots = await db.insight_snapshots.findOne(
            { where },
            { transaction },
        );

        if (!insight_snapshots) {
            return insight_snapshots;
        }

        const output = insight_snapshots.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner = await insight_snapshots.getOwner({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.users,
        as: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.content_ref) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'insight_snapshots',
                        'content_ref',
                        filter.content_ref,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            window_start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    window_end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

            
            if (filter.window_start_atRange) {
                const [start, end] = filter.window_start_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    window_start_at: {
                    ...where.window_start_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    window_start_at: {
                    ...where.window_start_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.window_end_atRange) {
                const [start, end] = filter.window_end_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    window_end_at: {
                    ...where.window_end_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    window_end_at: {
                    ...where.window_end_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.impressionsRange) {
                const [start, end] = filter.impressionsRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    impressions: {
                    ...where.impressions,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    impressions: {
                    ...where.impressions,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.reachRange) {
                const [start, end] = filter.reachRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    reach: {
                    ...where.reach,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    reach: {
                    ...where.reach,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.profile_visitsRange) {
                const [start, end] = filter.profile_visitsRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    profile_visits: {
                    ...where.profile_visits,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    profile_visits: {
                    ...where.profile_visits,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.likesRange) {
                const [start, end] = filter.likesRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    likes: {
                    ...where.likes,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    likes: {
                    ...where.likes,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.commentsRange) {
                const [start, end] = filter.commentsRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    comments: {
                    ...where.comments,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    comments: {
                    ...where.comments,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.savesRange) {
                const [start, end] = filter.savesRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    saves: {
                    ...where.saves,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    saves: {
                    ...where.saves,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.sharesRange) {
                const [start, end] = filter.sharesRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    shares: {
                    ...where.shares,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    shares: {
                    ...where.shares,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.content_type) {
                where = {
                    ...where,
                content_type: filter.content_type,
            };
            }
            


      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.insight_snapshots.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'insight_snapshots',
                        'content_ref',
                        query,
                    ),
                ],
            };
        }

        const records = await db.insight_snapshots.findAll({
            attributes: [ 'id', 'content_ref' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['content_ref', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.content_ref,
        }));
    }

    
};

