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

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

        const broker_connections = await db.broker_connections.create(
            {
                id: data.id || undefined,
        
        broker: data.broker
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        connection_label: data.connection_label
        ||
        null
            ,
            
        sync_enabled: data.sync_enabled
        ||
        false
        
            ,
            
        last_sync_at: data.last_sync_at
        ||
        null
            ,
            
        last_error: data.last_error
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await broker_connections.setTrading_account( data.trading_account || null, {
            transaction,
        });
        

        

        

        return broker_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 broker_connectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                broker: item.broker
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                connection_label: item.connection_label
            ||
            null
            ,
            
                sync_enabled: item.sync_enabled
            ||
            false
        
            ,
            
                last_sync_at: item.last_sync_at
            ||
            null
            ,
            
                last_error: item.last_error
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return broker_connections;
    }

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

        const broker_connections = await db.broker_connections.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.broker !== undefined) updatePayload.broker = data.broker;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.connection_label !== undefined) updatePayload.connection_label = data.connection_label;
        
        
        if (data.sync_enabled !== undefined) updatePayload.sync_enabled = data.sync_enabled;
        
        
        if (data.last_sync_at !== undefined) updatePayload.last_sync_at = data.last_sync_at;
        
        
        if (data.last_error !== undefined) updatePayload.last_error = data.last_error;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trading_account !== undefined) {
            await broker_connections.setTrading_account(
              
              data.trading_account,
              
              { transaction }
            );
        }
        

        
        

        

        return broker_connections;
    }

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

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

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


        return broker_connections;
    }

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

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

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

        await broker_connections.destroy({
            transaction
        });

        return broker_connections;
    }

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

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

        if (!broker_connections) {
            return broker_connections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.trade_sync_runs_broker_connection = await broker_connections.getTrade_sync_runs_broker_connection({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.trading_account = await broker_connections.getTrading_account({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.trading_accounts,
        as: 'trading_account',
        
        where: filter.trading_account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trading_account.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.trading_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.connection_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'broker_connections',
                        'connection_label',
                        filter.connection_label,
                    ),
                };
            }
            
            if (filter.last_error) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'broker_connections',
                        'last_error',
                        filter.last_error,
                    ),
                };
            }
            

            
            

            
            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.broker) {
                where = {
                    ...where,
                broker: filter.broker,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.sync_enabled) {
                where = {
                    ...where,
                sync_enabled: filter.sync_enabled,
            };
            }
            


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.broker_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'broker_connections',
                        'connection_label',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

