
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,
        
        full_name: data.full_name
        ||
        null
            ,
            
        phone_number: data.phone_number
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        topic: data.topic
        ||
        null
            ,
            
        message: data.message
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { 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,
                
                full_name: item.full_name
            ||
            null
            ,
            
                phone_number: item.phone_number
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                topic: item.topic
            ||
            null
            ,
            
                message: item.message
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                status: item.status
            ||
            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.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.topic !== undefined) updatePayload.topic = data.topic;
        
        
        if (data.message !== undefined) updatePayload.message = data.message;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

        await contact_messages.update(updatePayload, {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});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contact_messages',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.phone_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contact_messages',
                        'phone_number',
                        filter.phone_number,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contact_messages',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contact_messages',
                        'message',
                        filter.message,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.topic) {
                where = {
                    ...where,
                topic: filter.topic,
            };
            }
            
            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',
                        'full_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

