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

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

        const reward_redemptions = await db.reward_redemptions.create(
            {
                id: data.id || undefined,
        
        quantity: data.quantity
        ||
        null
            ,
            
        coins_spent: data.coins_spent
        ||
        null
            ,
            
        fulfillment_status: data.fulfillment_status
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        fulfilled_at: data.fulfilled_at
        ||
        null
            ,
            
        fulfillment_note: data.fulfillment_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await reward_redemptions.setReward_catalog_item( data.reward_catalog_item || null, {
            transaction,
        });
        
        await reward_redemptions.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await reward_redemptions.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return reward_redemptions;
    }
    

    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 reward_redemptionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quantity: item.quantity
            ||
            null
            ,
            
                coins_spent: item.coins_spent
            ||
            null
            ,
            
                fulfillment_status: item.fulfillment_status
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                fulfilled_at: item.fulfilled_at
            ||
            null
            ,
            
                fulfillment_note: item.fulfillment_note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return reward_redemptions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.coins_spent !== undefined) updatePayload.coins_spent = data.coins_spent;
        
        
        if (data.fulfillment_status !== undefined) updatePayload.fulfillment_status = data.fulfillment_status;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.fulfilled_at !== undefined) updatePayload.fulfilled_at = data.fulfilled_at;
        
        
        if (data.fulfillment_note !== undefined) updatePayload.fulfillment_note = data.fulfillment_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.reward_catalog_item !== undefined) {
            await reward_redemptions.setReward_catalog_item(
              
              data.reward_catalog_item,
              
              { transaction }
            );
        }
        
        if (data.organization !== undefined) {
            await reward_redemptions.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await reward_redemptions.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return reward_redemptions;
    }

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

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

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


        return reward_redemptions;
    }

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

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

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

        await reward_redemptions.destroy({
            transaction
        });

        return reward_redemptions;
    }

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

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

        if (!reward_redemptions) {
            return reward_redemptions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reward_catalog_item = await reward_redemptions.getReward_catalog_item({
            transaction
        });
        
        
        output.organization = await reward_redemptions.getOrganization({
            transaction
        });
        
        
        output.user = await reward_redemptions.getUser({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.organizations,
        as: 'organization',
        
      },

      {
        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.fulfillment_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reward_redemptions',
                        'fulfillment_note',
                        filter.fulfillment_note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[Op.or]: listItems}
        };
      }
      

      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.reward_redemptions.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'reward_redemptions',
                        'fulfillment_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

