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

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

        const activities = await db.activities.create(
            {
                id: data.id || undefined,
        
        activity_type: data.activity_type
        ||
        null
            ,
            
        subject: data.subject
        ||
        null
            ,
            
        details: data.details
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await activities.setCompany( data.company || null, {
            transaction,
        });
        
        await activities.setLead( data.lead || null, {
            transaction,
        });
        
        await activities.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        

        

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

        return activities;
    }
    

    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 activitiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                activity_type: item.activity_type
            ||
            null
            ,
            
                subject: item.subject
            ||
            null
            ,
            
                details: item.details
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                completed_at: item.completed_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 activities = await db.activities.bulkCreate(activitiesData, { transaction });

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

        return activities;
    }

    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 activities = await db.activities.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.activity_type !== undefined) updatePayload.activity_type = data.activity_type;
        
        
        if (data.subject !== undefined) updatePayload.subject = data.subject;
        
        
        if (data.details !== undefined) updatePayload.details = data.details;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await activities.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.lead !== undefined) {
            await activities.setLead(
              
              data.lead,
              
              { transaction }
            );
        }
        
        if (data.assigned_to !== undefined) {
            await activities.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        

        
        

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

        return activities;
    }

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

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

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


        return activities;
    }

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

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

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

        await activities.destroy({
            transaction
        });

        return activities;
    }

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

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

        if (!activities) {
            return activities;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await activities.getCompany({
            transaction
        });
        
        
        output.lead = await activities.getLead({
            transaction
        });
        
        
        output.assigned_to = await activities.getAssigned_to({
            transaction
        });
        
        
        output.attachments = await activities.getAttachments({
            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 userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.companies,
        as: 'company',
        
      },

      {
        model: db.leads,
        as: 'lead',
        
        where: filter.lead ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.lead.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: 'attachments',
      },

    ];

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

            
            if (filter.subject) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'activities',
                        'subject',
                        filter.subject,
                    ),
                };
            }
            
            if (filter.details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'activities',
                        'details',
                        filter.details,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            scheduled_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    completed_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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


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

        where = {
          ...where,
          companyId: {[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.companiesId;
        }
        

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

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

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

    
};

