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

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

        const trade_sync_runs = await db.trade_sync_runs.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
        created_trades: data.created_trades
        ||
        null
            ,
            
        updated_trades: data.updated_trades
        ||
        null
            ,
            
        skipped_trades: data.skipped_trades
        ||
        null
            ,
            
        error_details: data.error_details
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trade_sync_runs.setBroker_connection( data.broker_connection || null, {
            transaction,
        });
        

        

        

        return trade_sync_runs;
    }
    

    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 trade_sync_runsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
                created_trades: item.created_trades
            ||
            null
            ,
            
                updated_trades: item.updated_trades
            ||
            null
            ,
            
                skipped_trades: item.skipped_trades
            ||
            null
            ,
            
                error_details: item.error_details
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trade_sync_runs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        if (data.created_trades !== undefined) updatePayload.created_trades = data.created_trades;
        
        
        if (data.updated_trades !== undefined) updatePayload.updated_trades = data.updated_trades;
        
        
        if (data.skipped_trades !== undefined) updatePayload.skipped_trades = data.skipped_trades;
        
        
        if (data.error_details !== undefined) updatePayload.error_details = data.error_details;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.broker_connection !== undefined) {
            await trade_sync_runs.setBroker_connection(
              
              data.broker_connection,
              
              { transaction }
            );
        }
        

        
        

        

        return trade_sync_runs;
    }

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

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

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


        return trade_sync_runs;
    }

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

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

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

        await trade_sync_runs.destroy({
            transaction
        });

        return trade_sync_runs;
    }

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

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

        if (!trade_sync_runs) {
            return trade_sync_runs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.broker_connection = await trade_sync_runs.getBroker_connection({
            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.broker_connections,
        as: 'broker_connection',
        
        where: filter.broker_connection ? {
          [Op.or]: [
            { id: { [Op.in]: filter.broker_connection.split('|').map(term => Utils.uuid(term)) } },
            {
              connection_label: {
                [Op.or]: filter.broker_connection.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.error_details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trade_sync_runs',
                        'error_details',
                        filter.error_details,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

