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

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

        const external_integrations = await db.external_integrations.create(
            {
                id: data.id || undefined,
        
        integration_type: data.integration_type
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        integration_status: data.integration_status
        ||
        null
            ,
            
        auth_reference: data.auth_reference
        ||
        null
            ,
            
        auto_create_tasks_enabled: data.auto_create_tasks_enabled
        ||
        false
        
            ,
            
        auto_schedule_followups_enabled: data.auto_schedule_followups_enabled
        ||
        false
        
            ,
            
        last_sync_at: data.last_sync_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await external_integrations.setTenant( data.tenant || null, {
            transaction,
        });
        
        await external_integrations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return external_integrations;
    }
    

    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 external_integrationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                integration_type: item.integration_type
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                integration_status: item.integration_status
            ||
            null
            ,
            
                auth_reference: item.auth_reference
            ||
            null
            ,
            
                auto_create_tasks_enabled: item.auto_create_tasks_enabled
            ||
            false
        
            ,
            
                auto_schedule_followups_enabled: item.auto_schedule_followups_enabled
            ||
            false
        
            ,
            
                last_sync_at: item.last_sync_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return external_integrations;
    }

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


        

        const updatePayload = {};
        
        if (data.integration_type !== undefined) updatePayload.integration_type = data.integration_type;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.integration_status !== undefined) updatePayload.integration_status = data.integration_status;
        
        
        if (data.auth_reference !== undefined) updatePayload.auth_reference = data.auth_reference;
        
        
        if (data.auto_create_tasks_enabled !== undefined) updatePayload.auto_create_tasks_enabled = data.auto_create_tasks_enabled;
        
        
        if (data.auto_schedule_followups_enabled !== undefined) updatePayload.auto_schedule_followups_enabled = data.auto_schedule_followups_enabled;
        
        
        if (data.last_sync_at !== undefined) updatePayload.last_sync_at = data.last_sync_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await external_integrations.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await external_integrations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return external_integrations;
    }

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

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

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


        return external_integrations;
    }

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

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

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

        await external_integrations.destroy({
            transaction
        });

        return external_integrations;
    }

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

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

        if (!external_integrations) {
            return external_integrations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tasks_external_integration = await external_integrations.getTasks_external_integration({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await external_integrations.getTenant({
            transaction
        });
        
        
        output.organizations = await external_integrations.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'external_integrations',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.auth_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'external_integrations',
                        'auth_reference',
                        filter.auth_reference,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.integration_type) {
                where = {
                    ...where,
                integration_type: filter.integration_type,
            };
            }
            
            if (filter.integration_status) {
                where = {
                    ...where,
                integration_status: filter.integration_status,
            };
            }
            
            if (filter.auto_create_tasks_enabled) {
                where = {
                    ...where,
                auto_create_tasks_enabled: filter.auto_create_tasks_enabled,
            };
            }
            
            if (filter.auto_schedule_followups_enabled) {
                where = {
                    ...where,
                auto_schedule_followups_enabled: filter.auto_schedule_followups_enabled,
            };
            }
            


      

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

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

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

    
};

