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

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

        const efris_connections = await db.efris_connections.create(
            {
                id: data.id || undefined,
        
        environment: data.environment
        ||
        null
            ,
            
        device_number: data.device_number
        ||
        null
            ,
            
        branch_code: data.branch_code
        ||
        null
            ,
            
        business_name_on_efris: data.business_name_on_efris
        ||
        null
            ,
            
        tin_on_efris: data.tin_on_efris
        ||
        null
            ,
            
        client_id: data.client_id
        ||
        null
            ,
            
        client_secret: data.client_secret
        ||
        null
            ,
            
        api_base_url: data.api_base_url
        ||
        null
            ,
            
        last_connected_at: data.last_connected_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        last_error_message: data.last_error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await efris_connections.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

        

        return efris_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 efris_connectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                environment: item.environment
            ||
            null
            ,
            
                device_number: item.device_number
            ||
            null
            ,
            
                branch_code: item.branch_code
            ||
            null
            ,
            
                business_name_on_efris: item.business_name_on_efris
            ||
            null
            ,
            
                tin_on_efris: item.tin_on_efris
            ||
            null
            ,
            
                client_id: item.client_id
            ||
            null
            ,
            
                client_secret: item.client_secret
            ||
            null
            ,
            
                api_base_url: item.api_base_url
            ||
            null
            ,
            
                last_connected_at: item.last_connected_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                last_error_message: item.last_error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.environment !== undefined) updatePayload.environment = data.environment;
        
        
        if (data.device_number !== undefined) updatePayload.device_number = data.device_number;
        
        
        if (data.branch_code !== undefined) updatePayload.branch_code = data.branch_code;
        
        
        if (data.business_name_on_efris !== undefined) updatePayload.business_name_on_efris = data.business_name_on_efris;
        
        
        if (data.tin_on_efris !== undefined) updatePayload.tin_on_efris = data.tin_on_efris;
        
        
        if (data.client_id !== undefined) updatePayload.client_id = data.client_id;
        
        
        if (data.client_secret !== undefined) updatePayload.client_secret = data.client_secret;
        
        
        if (data.api_base_url !== undefined) updatePayload.api_base_url = data.api_base_url;
        
        
        if (data.last_connected_at !== undefined) updatePayload.last_connected_at = data.last_connected_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.last_error_message !== undefined) updatePayload.last_error_message = data.last_error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await efris_connections.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

        

        return efris_connections;
    }

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

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

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


        return efris_connections;
    }

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

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

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

        await efris_connections.destroy({
            transaction
        });

        return efris_connections;
    }

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

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

        if (!efris_connections) {
            return efris_connections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await efris_connections.getOrganization({
            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.organizations,
        as: 'organization',
        
      },



    ];

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

            
            if (filter.device_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_connections',
                        'device_number',
                        filter.device_number,
                    ),
                };
            }
            
            if (filter.branch_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_connections',
                        'branch_code',
                        filter.branch_code,
                    ),
                };
            }
            
            if (filter.business_name_on_efris) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_connections',
                        'business_name_on_efris',
                        filter.business_name_on_efris,
                    ),
                };
            }
            
            if (filter.tin_on_efris) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_connections',
                        'tin_on_efris',
                        filter.tin_on_efris,
                    ),
                };
            }
            
            if (filter.client_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_connections',
                        'client_id',
                        filter.client_id,
                    ),
                };
            }
            
            if (filter.client_secret) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_connections',
                        'client_secret',
                        filter.client_secret,
                    ),
                };
            }
            
            if (filter.api_base_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_connections',
                        'api_base_url',
                        filter.api_base_url,
                    ),
                };
            }
            
            if (filter.last_error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_connections',
                        'last_error_message',
                        filter.last_error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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


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

        where = {
          ...where,
          organizationId: {[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.efris_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(
                        'efris_connections',
                        'device_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

