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

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

        const notification_events = await db.notification_events.create(
            {
                id: data.id || undefined,
        
        event_type: data.event_type
        ||
        null
            ,
            
        audience: data.audience
        ||
        null
            ,
            
        order_nature: data.order_nature
        ||
        null
            ,
            
        quantity_total: data.quantity_total
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        message: data.message
        ||
        null
            ,
            
        event_time: data.event_time
        ||
        null
            ,
            
        is_read: data.is_read
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await notification_events.setRestaurant( data.restaurant || null, {
            transaction,
        });
        
        await notification_events.setTarget_user( data.target_user || null, {
            transaction,
        });
        

        

        

        return notification_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 notification_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                event_type: item.event_type
            ||
            null
            ,
            
                audience: item.audience
            ||
            null
            ,
            
                order_nature: item.order_nature
            ||
            null
            ,
            
                quantity_total: item.quantity_total
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                message: item.message
            ||
            null
            ,
            
                event_time: item.event_time
            ||
            null
            ,
            
                is_read: item.is_read
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return notification_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
        
        
        if (data.audience !== undefined) updatePayload.audience = data.audience;
        
        
        if (data.order_nature !== undefined) updatePayload.order_nature = data.order_nature;
        
        
        if (data.quantity_total !== undefined) updatePayload.quantity_total = data.quantity_total;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.message !== undefined) updatePayload.message = data.message;
        
        
        if (data.event_time !== undefined) updatePayload.event_time = data.event_time;
        
        
        if (data.is_read !== undefined) updatePayload.is_read = data.is_read;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.restaurant !== undefined) {
            await notification_events.setRestaurant(
              
              data.restaurant,
              
              { transaction }
            );
        }
        
        if (data.target_user !== undefined) {
            await notification_events.setTarget_user(
              
              data.target_user,
              
              { transaction }
            );
        }
        

        
        

        

        return notification_events;
    }

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

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

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


        return notification_events;
    }

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

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

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

        await notification_events.destroy({
            transaction
        });

        return notification_events;
    }

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

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

        if (!notification_events) {
            return notification_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.restaurant = await notification_events.getRestaurant({
            transaction
        });
        
        
        output.target_user = await notification_events.getTarget_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.restaurants,
        as: 'restaurant',
        
        where: filter.restaurant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.restaurant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.restaurant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'notification_events',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'notification_events',
                        'message',
                        filter.message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.event_type) {
                where = {
                    ...where,
                event_type: filter.event_type,
            };
            }
            
            if (filter.audience) {
                where = {
                    ...where,
                audience: filter.audience,
            };
            }
            
            if (filter.order_nature) {
                where = {
                    ...where,
                order_nature: filter.order_nature,
            };
            }
            
            if (filter.is_read) {
                where = {
                    ...where,
                is_read: filter.is_read,
            };
            }
            


      

      



            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.notification_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(
                        'notification_events',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

