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

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

        const daily_rewards = await db.daily_rewards.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        reward_type: data.reward_type
        ||
        null
            ,
            
        day_index: data.day_index
        ||
        null
            ,
            
        yux_amount: data.yux_amount
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await daily_rewards.setBox( data.box || null, {
            transaction,
        });
        
        await daily_rewards.setCosmetic( data.cosmetic || null, {
            transaction,
        });
        
        await daily_rewards.setTitle_item( data.title_item || null, {
            transaction,
        });
        
        await daily_rewards.setBadge( data.badge || null, {
            transaction,
        });
        

        

        

        return daily_rewards;
    }
    

    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_rewardsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                reward_type: item.reward_type
            ||
            null
            ,
            
                day_index: item.day_index
            ||
            null
            ,
            
                yux_amount: item.yux_amount
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return daily_rewards;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.reward_type !== undefined) updatePayload.reward_type = data.reward_type;
        
        
        if (data.day_index !== undefined) updatePayload.day_index = data.day_index;
        
        
        if (data.yux_amount !== undefined) updatePayload.yux_amount = data.yux_amount;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.box !== undefined) {
            await daily_rewards.setBox(
              
              data.box,
              
              { transaction }
            );
        }
        
        if (data.cosmetic !== undefined) {
            await daily_rewards.setCosmetic(
              
              data.cosmetic,
              
              { transaction }
            );
        }
        
        if (data.title_item !== undefined) {
            await daily_rewards.setTitle_item(
              
              data.title_item,
              
              { transaction }
            );
        }
        
        if (data.badge !== undefined) {
            await daily_rewards.setBadge(
              
              data.badge,
              
              { transaction }
            );
        }
        

        
        

        

        return daily_rewards;
    }

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

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

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


        return daily_rewards;
    }

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

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

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

        await daily_rewards.destroy({
            transaction
        });

        return daily_rewards;
    }

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

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

        if (!daily_rewards) {
            return daily_rewards;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.box = await daily_rewards.getBox({
            transaction
        });
        
        
        output.cosmetic = await daily_rewards.getCosmetic({
            transaction
        });
        
        
        output.title_item = await daily_rewards.getTitle_item({
            transaction
        });
        
        
        output.badge = await daily_rewards.getBadge({
            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.boxes,
        as: 'box',
        
        where: filter.box ? {
          [Op.or]: [
            { id: { [Op.in]: filter.box.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.box.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

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

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    yux_amount: {
                    ...where.yux_amount,
                            [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.is_enabled) {
                where = {
                    ...where,
                is_enabled: filter.is_enabled,
            };
            }
            


      

      

      

      



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

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

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

    
};

