
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 Trending_entriesDBApi {
    

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

        const trending_entries = await db.trending_entries.create(
            {
                id: data.id || undefined,
        
        window: data.window
        ||
        null
            ,
            
        rank: data.rank
        ||
        null
            ,
            
        trend_score: data.trend_score
        ||
        null
            ,
            
        as_of_at: data.as_of_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trending_entries.setTitle( data.title || null, {
            transaction,
        });
        

        

        

        return trending_entries;
    }
    

    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 trending_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                window: item.window
            ||
            null
            ,
            
                rank: item.rank
            ||
            null
            ,
            
                trend_score: item.trend_score
            ||
            null
            ,
            
                as_of_at: item.as_of_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trending_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.window !== undefined) updatePayload.window = data.window;
        
        
        if (data.rank !== undefined) updatePayload.rank = data.rank;
        
        
        if (data.trend_score !== undefined) updatePayload.trend_score = data.trend_score;
        
        
        if (data.as_of_at !== undefined) updatePayload.as_of_at = data.as_of_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.title !== undefined) {
            await trending_entries.setTitle(
              
              data.title,
              
              { transaction }
            );
        }
        

        
        

        

        return trending_entries;
    }

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

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

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


        return trending_entries;
    }

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

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

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

        await trending_entries.destroy({
            transaction
        });

        return trending_entries;
    }

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

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

        if (!trending_entries) {
            return trending_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.title = await trending_entries.getTitle({
            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.titles,
        as: 'title',
        
        where: filter.title ? {
          [Op.or]: [
            { id: { [Op.in]: filter.title.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.title.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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


      



            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.trending_entries.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(
                        'trending_entries',
                        'window',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

