
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,
        
        title: data.title
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        estimated_value: data.estimated_value
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        next_follow_up_at: data.next_follow_up_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await leads.setCompany( data.company || null, {
            transaction,
        });
        
        await leads.setPrimary_contact( data.primary_contact || null, {
            transaction,
        });
        
        await leads.setOwner( data.owner || null, {
            transaction,
        });
        
        await leads.setPipeline( data.pipeline || null, {
            transaction,
        });
        
        await leads.setStage( data.stage || null, {
            transaction,
        });
        
        await leads.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        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,
                
                title: item.title
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                estimated_value: item.estimated_value
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                next_follow_up_at: item.next_follow_up_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
            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
        

        return leads;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.estimated_value !== undefined) updatePayload.estimated_value = data.estimated_value;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.next_follow_up_at !== undefined) updatePayload.next_follow_up_at = data.next_follow_up_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await leads.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.primary_contact !== undefined) {
            await leads.setPrimary_contact(
              
              data.primary_contact,
              
              { transaction }
            );
        }
        
        if (data.owner !== undefined) {
            await leads.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.pipeline !== undefined) {
            await leads.setPipeline(
              
              data.pipeline,
              
              { transaction }
            );
        }
        
        if (data.stage !== undefined) {
            await leads.setStage(
              
              data.stage,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await leads.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        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.deals_lead = await leads.getDeals_lead({
            transaction
        });
        
        
        output.activities_lead = await leads.getActivities_lead({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await leads.getCompany({
            transaction
        });
        
        
        output.primary_contact = await leads.getPrimary_contact({
            transaction
        });
        
        
        output.owner = await leads.getOwner({
            transaction
        });
        
        
        output.pipeline = await leads.getPipeline({
            transaction
        });
        
        
        output.stage = await leads.getStage({
            transaction
        });
        
        
        output.organizations = await leads.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'leads',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'leads',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.source) {
                where = {
                    ...where,
                source: filter.source,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'leads',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

