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

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

        const leads = await db.leads.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        preferred_contact_method: data.preferred_contact_method
        ||
        null
            ,
            
        message: data.message
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
        stage: data.stage
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        follow_up_at: data.follow_up_at
        ||
        null
            ,
            
        consent_to_contact: data.consent_to_contact
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await leads.setService( data.service || null, {
            transaction,
        });
        
        await leads.setProject( data.project || null, {
            transaction,
        });
        
        await leads.setAssigned_user( data.assigned_user || null, {
            transaction,
        });
        

        

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

        return leads;
    }
    

    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 leadsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                preferred_contact_method: item.preferred_contact_method
            ||
            null
            ,
            
                message: item.message
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
                stage: item.stage
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                follow_up_at: item.follow_up_at
            ||
            null
            ,
            
                consent_to_contact: item.consent_to_contact
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return leads;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.preferred_contact_method !== undefined) updatePayload.preferred_contact_method = data.preferred_contact_method;
        
        
        if (data.message !== undefined) updatePayload.message = data.message;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.stage !== undefined) updatePayload.stage = data.stage;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.follow_up_at !== undefined) updatePayload.follow_up_at = data.follow_up_at;
        
        
        if (data.consent_to_contact !== undefined) updatePayload.consent_to_contact = data.consent_to_contact;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.service !== undefined) {
            await leads.setService(
              
              data.service,
              
              { transaction }
            );
        }
        
        if (data.project !== undefined) {
            await leads.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.assigned_user !== undefined) {
            await leads.setAssigned_user(
              
              data.assigned_user,
              
              { transaction }
            );
        }
        

        
        

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

        return leads;
    }

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

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

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


        return leads;
    }

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

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

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

        await leads.destroy({
            transaction
        });

        return leads;
    }

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

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

        if (!leads) {
            return leads;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.service = await leads.getService({
            transaction
        });
        
        
        output.project = await leads.getProject({
            transaction
        });
        
        
        output.attachment_files = await leads.getAttachment_files({
            transaction
        });
        
        
        output.assigned_user = await leads.getAssigned_user({
            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.services,
        as: 'service',
        
        where: filter.service ? {
          [Op.or]: [
            { id: { [Op.in]: filter.service.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.service.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.preferred_contact_method) {
                where = {
                    ...where,
                preferred_contact_method: filter.preferred_contact_method,
            };
            }
            
            if (filter.source) {
                where = {
                    ...where,
                source: filter.source,
            };
            }
            
            if (filter.stage) {
                where = {
                    ...where,
                stage: filter.stage,
            };
            }
            
            if (filter.consent_to_contact) {
                where = {
                    ...where,
                consent_to_contact: filter.consent_to_contact,
            };
            }
            


      

      

      



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

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

    
};

