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

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

        const integrations = await db.integrations.create(
            {
                id: data.id || undefined,
        
        service: data.service
        ||
        null
            ,
            
        auth_type: data.auth_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        connected_at: data.connected_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        account_label: data.account_label
        ||
        null
            ,
            
        scopes: data.scopes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await integrations.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await integrations.setUser( data.user || null, {
            transaction,
        });
        
        await integrations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return 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 integrationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                service: item.service
            ||
            null
            ,
            
                auth_type: item.auth_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                connected_at: item.connected_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                account_label: item.account_label
            ||
            null
            ,
            
                scopes: item.scopes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.service !== undefined) updatePayload.service = data.service;
        
        
        if (data.auth_type !== undefined) updatePayload.auth_type = data.auth_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.connected_at !== undefined) updatePayload.connected_at = data.connected_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.account_label !== undefined) updatePayload.account_label = data.account_label;
        
        
        if (data.scopes !== undefined) updatePayload.scopes = data.scopes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await integrations.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await integrations.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await integrations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return integrations;
    }

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

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

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


        return integrations;
    }

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

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

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

        await integrations.destroy({
            transaction
        });

        return integrations;
    }

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

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

        if (!integrations) {
            return integrations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.calendar_events_integration = await integrations.getCalendar_events_integration({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.workspace = await integrations.getWorkspace({
            transaction
        });
        
        
        output.user = await integrations.getUser({
            transaction
        });
        
        
        output.organizations = await 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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.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.account_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'integrations',
                        'account_label',
                        filter.account_label,
                    ),
                };
            }
            
            if (filter.scopes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'integrations',
                        'scopes',
                        filter.scopes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.service) {
                where = {
                    ...where,
                service: filter.service,
            };
            }
            
            if (filter.auth_type) {
                where = {
                    ...where,
                auth_type: filter.auth_type,
            };
            }
            
            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.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(
                        'integrations',
                        'account_label',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

