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

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

        const wheel_events = await db.wheel_events.create(
            {
                id: data.id || undefined,
        
        trigger_question_index: data.trigger_question_index
        ||
        null
            ,
            
        reward_type: data.reward_type
        ||
        null
            ,
            
        multiplier_value: data.multiplier_value
        ||
        null
            ,
            
        bonus_points: data.bonus_points
        ||
        null
            ,
            
        bonus_yux: data.bonus_yux
        ||
        null
            ,
            
        music_track: data.music_track
        ||
        null
            ,
            
        event_started_at: data.event_started_at
        ||
        null
            ,
            
        event_ended_at: data.event_ended_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await wheel_events.setMatch( data.match || null, {
            transaction,
        });
        

        

        

        return wheel_events;
    }
    

    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 wheel_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                trigger_question_index: item.trigger_question_index
            ||
            null
            ,
            
                reward_type: item.reward_type
            ||
            null
            ,
            
                multiplier_value: item.multiplier_value
            ||
            null
            ,
            
                bonus_points: item.bonus_points
            ||
            null
            ,
            
                bonus_yux: item.bonus_yux
            ||
            null
            ,
            
                music_track: item.music_track
            ||
            null
            ,
            
                event_started_at: item.event_started_at
            ||
            null
            ,
            
                event_ended_at: item.event_ended_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return wheel_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.trigger_question_index !== undefined) updatePayload.trigger_question_index = data.trigger_question_index;
        
        
        if (data.reward_type !== undefined) updatePayload.reward_type = data.reward_type;
        
        
        if (data.multiplier_value !== undefined) updatePayload.multiplier_value = data.multiplier_value;
        
        
        if (data.bonus_points !== undefined) updatePayload.bonus_points = data.bonus_points;
        
        
        if (data.bonus_yux !== undefined) updatePayload.bonus_yux = data.bonus_yux;
        
        
        if (data.music_track !== undefined) updatePayload.music_track = data.music_track;
        
        
        if (data.event_started_at !== undefined) updatePayload.event_started_at = data.event_started_at;
        
        
        if (data.event_ended_at !== undefined) updatePayload.event_ended_at = data.event_ended_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.match !== undefined) {
            await wheel_events.setMatch(
              
              data.match,
              
              { transaction }
            );
        }
        

        
        

        

        return wheel_events;
    }

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

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

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


        return wheel_events;
    }

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

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

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

        await wheel_events.destroy({
            transaction
        });

        return wheel_events;
    }

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

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

        if (!wheel_events) {
            return wheel_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.match = await wheel_events.getMatch({
            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.matches,
        as: 'match',
        
        where: filter.match ? {
          [Op.or]: [
            { id: { [Op.in]: filter.match.split('|').map(term => Utils.uuid(term)) } },
            {
              game_code: {
                [Op.or]: filter.match.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

