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

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

        const whatsapp_notifications = await db.whatsapp_notifications.create(
            {
                id: data.id || undefined,
        
        event_type: data.event_type
        ||
        null
            ,
            
        to_number: data.to_number
        ||
        null
            ,
            
        message_body: data.message_body
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        queued_at: data.queued_at
        ||
        null
            ,
            
        sent_at: data.sent_at
        ||
        null
            ,
            
        provider_message_id: data.provider_message_id
        ||
        null
            ,
            
        error_details: data.error_details
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await whatsapp_notifications.setRepair_order( data.repair_order || null, {
            transaction,
        });
        

        

        

        return whatsapp_notifications;
    }
    

    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 whatsapp_notificationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                event_type: item.event_type
            ||
            null
            ,
            
                to_number: item.to_number
            ||
            null
            ,
            
                message_body: item.message_body
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                queued_at: item.queued_at
            ||
            null
            ,
            
                sent_at: item.sent_at
            ||
            null
            ,
            
                provider_message_id: item.provider_message_id
            ||
            null
            ,
            
                error_details: item.error_details
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return whatsapp_notifications;
    }

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

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


        

        const updatePayload = {};
        
        if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
        
        
        if (data.to_number !== undefined) updatePayload.to_number = data.to_number;
        
        
        if (data.message_body !== undefined) updatePayload.message_body = data.message_body;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.queued_at !== undefined) updatePayload.queued_at = data.queued_at;
        
        
        if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
        
        
        if (data.provider_message_id !== undefined) updatePayload.provider_message_id = data.provider_message_id;
        
        
        if (data.error_details !== undefined) updatePayload.error_details = data.error_details;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.repair_order !== undefined) {
            await whatsapp_notifications.setRepair_order(
              
              data.repair_order,
              
              { transaction }
            );
        }
        

        
        

        

        return whatsapp_notifications;
    }

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

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

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


        return whatsapp_notifications;
    }

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

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

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

        await whatsapp_notifications.destroy({
            transaction
        });

        return whatsapp_notifications;
    }

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

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

        if (!whatsapp_notifications) {
            return whatsapp_notifications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.repair_order = await whatsapp_notifications.getRepair_order({
            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.repair_orders,
        as: 'repair_order',
        
        where: filter.repair_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.repair_order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.repair_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.to_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'whatsapp_notifications',
                        'to_number',
                        filter.to_number,
                    ),
                };
            }
            
            if (filter.message_body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'whatsapp_notifications',
                        'message_body',
                        filter.message_body,
                    ),
                };
            }
            
            if (filter.provider_message_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'whatsapp_notifications',
                        'provider_message_id',
                        filter.provider_message_id,
                    ),
                };
            }
            
            if (filter.error_details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'whatsapp_notifications',
                        'error_details',
                        filter.error_details,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    sent_at: {
                    ...where.sent_at,
                            [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.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.whatsapp_notifications.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(
                        'whatsapp_notifications',
                        'event_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

