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

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

        const data_connections = await db.data_connections.create(
            {
                id: data.id || undefined,
        
        provider_type: data.provider_type
        ||
        null
            ,
            
        provider_name: data.provider_name
        ||
        null
            ,
            
        connection_status: data.connection_status
        ||
        null
            ,
            
        connected_at: data.connected_at
        ||
        null
            ,
            
        last_sync_at: data.last_sync_at
        ||
        null
            ,
            
        external_reference: data.external_reference
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return data_connections;
    }
    

    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 data_connectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider_type: item.provider_type
            ||
            null
            ,
            
                provider_name: item.provider_name
            ||
            null
            ,
            
                connection_status: item.connection_status
            ||
            null
            ,
            
                connected_at: item.connected_at
            ||
            null
            ,
            
                last_sync_at: item.last_sync_at
            ||
            null
            ,
            
                external_reference: item.external_reference
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return data_connections;
    }

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


        

        const updatePayload = {};
        
        if (data.provider_type !== undefined) updatePayload.provider_type = data.provider_type;
        
        
        if (data.provider_name !== undefined) updatePayload.provider_name = data.provider_name;
        
        
        if (data.connection_status !== undefined) updatePayload.connection_status = data.connection_status;
        
        
        if (data.connected_at !== undefined) updatePayload.connected_at = data.connected_at;
        
        
        if (data.last_sync_at !== undefined) updatePayload.last_sync_at = data.last_sync_at;
        
        
        if (data.external_reference !== undefined) updatePayload.external_reference = data.external_reference;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return data_connections;
    }

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

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

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


        return data_connections;
    }

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

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

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

        await data_connections.destroy({
            transaction
        });

        return data_connections;
    }

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

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

        if (!data_connections) {
            return data_connections;
        }

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

        
        
        
        
        
        
        
        
        output.financial_accounts_data_connection = await data_connections.getFinancial_accounts_data_connection({
            transaction
        });
        
        
        
        
        output.transactions_data_connection = await data_connections.getTransactions_data_connection({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sync_jobs_data_connection = await data_connections.getSync_jobs_data_connection({
            transaction
        });
        
        
        
        output.workspace = await data_connections.getWorkspace({
            transaction
        });
        
        
        output.organizations = await data_connections.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.provider_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'data_connections',
                        'provider_name',
                        filter.provider_name,
                    ),
                };
            }
            
            if (filter.external_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'data_connections',
                        'external_reference',
                        filter.external_reference,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'data_connections',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

            
            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.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.provider_type) {
                where = {
                    ...where,
                provider_type: filter.provider_type,
            };
            }
            
            if (filter.connection_status) {
                where = {
                    ...where,
                connection_status: filter.connection_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.data_connections.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(
                        'data_connections',
                        'provider_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

