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

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

        const message_recipients = await db.message_recipients.create(
            {
                id: data.id || undefined,
        
        read_at: data.read_at
        ||
        null
            ,
            
        delivery_status: data.delivery_status
        ||
        null
            ,
            
        archived: data.archived
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await message_recipients.setMessage( data.message || null, {
            transaction,
        });
        
        await message_recipients.setRecipient( data.recipient || null, {
            transaction,
        });
        

        

        

        return message_recipients;
    }
    

    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 message_recipientsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                read_at: item.read_at
            ||
            null
            ,
            
                delivery_status: item.delivery_status
            ||
            null
            ,
            
                archived: item.archived
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return message_recipients;
    }

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

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


        

        const updatePayload = {};
        
        if (data.read_at !== undefined) updatePayload.read_at = data.read_at;
        
        
        if (data.delivery_status !== undefined) updatePayload.delivery_status = data.delivery_status;
        
        
        if (data.archived !== undefined) updatePayload.archived = data.archived;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.message !== undefined) {
            await message_recipients.setMessage(
              
              data.message,
              
              { transaction }
            );
        }
        
        if (data.recipient !== undefined) {
            await message_recipients.setRecipient(
              
              data.recipient,
              
              { transaction }
            );
        }
        

        
        

        

        return message_recipients;
    }

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

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

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


        return message_recipients;
    }

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

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

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

        await message_recipients.destroy({
            transaction
        });

        return message_recipients;
    }

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

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

        if (!message_recipients) {
            return message_recipients;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.message = await message_recipients.getMessage({
            transaction
        });
        
        
        output.recipient = await message_recipients.getRecipient({
            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.messages,
        as: 'message',
        
        where: filter.message ? {
          [Op.or]: [
            { id: { [Op.in]: filter.message.split('|').map(term => Utils.uuid(term)) } },
            {
              subject: {
                [Op.or]: filter.message.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

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


      

      



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

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

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

    
};

