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

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

        const lead_requests = await db.lead_requests.create(
            {
                id: data.id || undefined,
        
        request_type: data.request_type
        ||
        null
            ,
            
        full_name: data.full_name
        ||
        null
            ,
            
        company_name: data.company_name
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        customer_type: data.customer_type
        ||
        null
            ,
            
        message_ar: data.message_ar
        ||
        null
            ,
            
        lead_status: data.lead_status
        ||
        null
            ,
            
        preferred_contact_time: data.preferred_contact_time
        ||
        null
            ,
            
        last_contacted_at: data.last_contacted_at
        ||
        null
            ,
            
        internal_notes: data.internal_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await lead_requests.setInterested_stone( data.interested_stone || null, {
            transaction,
        });
        
        await lead_requests.setInterested_service( data.interested_service || null, {
            transaction,
        });
        
        await lead_requests.setRelated_project( data.related_project || null, {
            transaction,
        });
        
        await lead_requests.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.lead_requests.getTableName(),
                belongsToColumn: 'reference_files',
                belongsToId: lead_requests.id,
            },
            data.reference_files,
            options,
        );
        

        return lead_requests;
    }
    

    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 lead_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                request_type: item.request_type
            ||
            null
            ,
            
                full_name: item.full_name
            ||
            null
            ,
            
                company_name: item.company_name
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                customer_type: item.customer_type
            ||
            null
            ,
            
                message_ar: item.message_ar
            ||
            null
            ,
            
                lead_status: item.lead_status
            ||
            null
            ,
            
                preferred_contact_time: item.preferred_contact_time
            ||
            null
            ,
            
                last_contacted_at: item.last_contacted_at
            ||
            null
            ,
            
                internal_notes: item.internal_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < lead_requests.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.lead_requests.getTableName(),
                    belongsToColumn: 'reference_files',
                    belongsToId: lead_requests[i].id,
                },
                data[i].reference_files,
                options,
            );
        }
        

        return lead_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.request_type !== undefined) updatePayload.request_type = data.request_type;
        
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.customer_type !== undefined) updatePayload.customer_type = data.customer_type;
        
        
        if (data.message_ar !== undefined) updatePayload.message_ar = data.message_ar;
        
        
        if (data.lead_status !== undefined) updatePayload.lead_status = data.lead_status;
        
        
        if (data.preferred_contact_time !== undefined) updatePayload.preferred_contact_time = data.preferred_contact_time;
        
        
        if (data.last_contacted_at !== undefined) updatePayload.last_contacted_at = data.last_contacted_at;
        
        
        if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.interested_stone !== undefined) {
            await lead_requests.setInterested_stone(
              
              data.interested_stone,
              
              { transaction }
            );
        }
        
        if (data.interested_service !== undefined) {
            await lead_requests.setInterested_service(
              
              data.interested_service,
              
              { transaction }
            );
        }
        
        if (data.related_project !== undefined) {
            await lead_requests.setRelated_project(
              
              data.related_project,
              
              { transaction }
            );
        }
        
        if (data.assigned_to !== undefined) {
            await lead_requests.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.lead_requests.getTableName(),
                belongsToColumn: 'reference_files',
                belongsToId: lead_requests.id,
            },
            data.reference_files,
            options,
        );
        

        return lead_requests;
    }

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

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

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


        return lead_requests;
    }

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

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

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

        await lead_requests.destroy({
            transaction
        });

        return lead_requests;
    }

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

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

        if (!lead_requests) {
            return lead_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quote_items_lead_request = await lead_requests.getQuote_items_lead_request({
            transaction
        });
        
        
        
        
        
        
        output.interested_stone = await lead_requests.getInterested_stone({
            transaction
        });
        
        
        output.interested_service = await lead_requests.getInterested_service({
            transaction
        });
        
        
        output.related_project = await lead_requests.getRelated_project({
            transaction
        });
        
        
        output.reference_files = await lead_requests.getReference_files({
            transaction
        });
        
        
        output.assigned_to = await lead_requests.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.stones,
        as: 'interested_stone',
        
        where: filter.interested_stone ? {
          [Op.or]: [
            { id: { [Op.in]: filter.interested_stone.split('|').map(term => Utils.uuid(term)) } },
            {
              name_ar: {
                [Op.or]: filter.interested_stone.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.projects,
        as: 'related_project',
        
        where: filter.related_project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.related_project.split('|').map(term => Utils.uuid(term)) } },
            {
              name_ar: {
                [Op.or]: filter.related_project.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}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'reference_files',
      },

    ];

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

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lead_requests',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lead_requests',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lead_requests',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lead_requests',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.message_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lead_requests',
                        'message_ar',
                        filter.message_ar,
                    ),
                };
            }
            
            if (filter.internal_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lead_requests',
                        'internal_notes',
                        filter.internal_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

        const records = await db.lead_requests.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,
        }));
    }

    
};

