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

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

        const contact_messages = await db.contact_messages.create(
            {
                id: data.id || undefined,
        
        sender_name: data.sender_name
        ||
        null
            ,
            
        sender_email: data.sender_email
        ||
        null
            ,
            
        sender_phone: data.sender_phone
        ||
        null
            ,
            
        subject: data.subject
        ||
        null
            ,
            
        message_body: data.message_body
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await contact_messages.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        

        

        

        return contact_messages;
    }
    

    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 contact_messagesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sender_name: item.sender_name
            ||
            null
            ,
            
                sender_email: item.sender_email
            ||
            null
            ,
            
                sender_phone: item.sender_phone
            ||
            null
            ,
            
                subject: item.subject
            ||
            null
            ,
            
                message_body: item.message_body
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return contact_messages;
    }

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

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


        

        const updatePayload = {};
        
        if (data.sender_name !== undefined) updatePayload.sender_name = data.sender_name;
        
        
        if (data.sender_email !== undefined) updatePayload.sender_email = data.sender_email;
        
        
        if (data.sender_phone !== undefined) updatePayload.sender_phone = data.sender_phone;
        
        
        if (data.subject !== undefined) updatePayload.subject = data.subject;
        
        
        if (data.message_body !== undefined) updatePayload.message_body = data.message_body;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.assigned_to !== undefined) {
            await contact_messages.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        

        
        

        

        return contact_messages;
    }

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

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

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


        return contact_messages;
    }

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

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

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

        await contact_messages.destroy({
            transaction
        });

        return contact_messages;
    }

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

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

        if (!contact_messages) {
            return contact_messages;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.assigned_to = await contact_messages.getAssigned_to({
            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.users,
        as: 'assigned_to',
        
        where: filter.assigned_to ? {
          [Op.or]: [
            { id: { [Op.in]: filter.assigned_to.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.assigned_to.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.sender_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contact_messages',
                        'sender_name',
                        filter.sender_name,
                    ),
                };
            }
            
            if (filter.sender_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contact_messages',
                        'sender_email',
                        filter.sender_email,
                    ),
                };
            }
            
            if (filter.sender_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contact_messages',
                        'sender_phone',
                        filter.sender_phone,
                    ),
                };
            }
            
            if (filter.subject) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contact_messages',
                        'subject',
                        filter.subject,
                    ),
                };
            }
            
            if (filter.message_body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contact_messages',
                        'message_body',
                        filter.message_body,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

    
};

