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

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

        const daily_sparks = await db.daily_sparks.create(
            {
                id: data.id || undefined,
        
        spark_date: data.spark_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        generation_model: data.generation_model
        ||
        null
            ,
            
        generation_cost: data.generation_cost
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await daily_sparks.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return daily_sparks;
    }
    

    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_sparksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                spark_date: item.spark_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                generation_model: item.generation_model
            ||
            null
            ,
            
                generation_cost: item.generation_cost
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return daily_sparks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.spark_date !== undefined) updatePayload.spark_date = data.spark_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.generation_model !== undefined) updatePayload.generation_model = data.generation_model;
        
        
        if (data.generation_cost !== undefined) updatePayload.generation_cost = data.generation_cost;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await daily_sparks.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return daily_sparks;
    }

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

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

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


        return daily_sparks;
    }

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

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

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

        await daily_sparks.destroy({
            transaction
        });

        return daily_sparks;
    }

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

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

        if (!daily_sparks) {
            return daily_sparks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.daily_spark_recommendations_daily_spark = await daily_sparks.getDaily_spark_recommendations_daily_spark({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.user = await daily_sparks.getUser({
            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: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

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

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

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

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

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

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

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

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


      



            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_sparks.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_sparks',
                        'generation_model',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

