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

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

        const daily_spark_recommendations = await db.daily_spark_recommendations.create(
            {
                id: data.id || undefined,
        
        rank: data.rank
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        shown_at: data.shown_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await daily_spark_recommendations.setDaily_spark( data.daily_spark || null, {
            transaction,
        });
        
        await daily_spark_recommendations.setRecommended_user( data.recommended_user || null, {
            transaction,
        });
        

        

        

        return daily_spark_recommendations;
    }
    

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

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

        // For each item created, replace relation files
        

        return daily_spark_recommendations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.rank !== undefined) updatePayload.rank = data.rank;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.shown_at !== undefined) updatePayload.shown_at = data.shown_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.daily_spark !== undefined) {
            await daily_spark_recommendations.setDaily_spark(
              
              data.daily_spark,
              
              { transaction }
            );
        }
        
        if (data.recommended_user !== undefined) {
            await daily_spark_recommendations.setRecommended_user(
              
              data.recommended_user,
              
              { transaction }
            );
        }
        

        
        

        

        return daily_spark_recommendations;
    }

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

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

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


        return daily_spark_recommendations;
    }

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

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

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

        await daily_spark_recommendations.destroy({
            transaction
        });

        return daily_spark_recommendations;
    }

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

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

        if (!daily_spark_recommendations) {
            return daily_spark_recommendations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.daily_spark = await daily_spark_recommendations.getDaily_spark({
            transaction
        });
        
        
        output.recommended_user = await daily_spark_recommendations.getRecommended_user({
            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.daily_sparks,
        as: 'daily_spark',
        
        where: filter.daily_spark ? {
          [Op.or]: [
            { id: { [Op.in]: filter.daily_spark.split('|').map(term => Utils.uuid(term)) } },
            {
              generation_model: {
                [Op.or]: filter.daily_spark.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

            
            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.shown_atRange) {
                const [start, end] = filter.shown_atRange;

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

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

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

            


      

      



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

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

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

    
};

