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

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

        const inquiries = await db.inquiries.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        subject_ar: data.subject_ar
        ||
        null
            ,
            
        message_ar: data.message_ar
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        replied_at: data.replied_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inquiries.setLocation( data.location || null, {
            transaction,
        });
        
        await inquiries.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        

        

        

        return inquiries;
    }
    

    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 inquiriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                subject_ar: item.subject_ar
            ||
            null
            ,
            
                message_ar: item.message_ar
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                replied_at: item.replied_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return inquiries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.subject_ar !== undefined) updatePayload.subject_ar = data.subject_ar;
        
        
        if (data.message_ar !== undefined) updatePayload.message_ar = data.message_ar;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.replied_at !== undefined) updatePayload.replied_at = data.replied_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return inquiries;
    }

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

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

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


        return inquiries;
    }

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

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

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

        await inquiries.destroy({
            transaction
        });

        return inquiries;
    }

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

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

        if (!inquiries) {
            return inquiries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.location = await inquiries.getLocation({
            transaction
        });
        
        
        output.assigned_to = await inquiries.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.contact_locations,
        as: 'location',
        
        where: filter.location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.location.split('|').map(term => Utils.uuid(term)) } },
            {
              name_ar: {
                [Op.or]: filter.location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.subject_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'subject_ar',
                        filter.subject_ar,
                    ),
                };
            }
            
            if (filter.message_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'message_ar',
                        filter.message_ar,
                    ),
                };
            }
            

            
            

            
            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.replied_atRange) {
                const [start, end] = filter.replied_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    replied_at: {
                    ...where.replied_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.inquiries.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(
                        'inquiries',
                        'subject_ar',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

