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

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

        const trade_rule_checks = await db.trade_rule_checks.create(
            {
                id: data.id || undefined,
        
        result: data.result
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        comment: data.comment
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trade_rule_checks.setTrade( data.trade || null, {
            transaction,
        });
        
        await trade_rule_checks.setTrade_rule( data.trade_rule || null, {
            transaction,
        });
        

        

        

        return trade_rule_checks;
    }
    

    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_rule_checksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                result: item.result
            ||
            null
            ,
            
                score: item.score
            ||
            null
            ,
            
                comment: item.comment
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trade_rule_checks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.result !== undefined) updatePayload.result = data.result;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.comment !== undefined) updatePayload.comment = data.comment;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trade !== undefined) {
            await trade_rule_checks.setTrade(
              
              data.trade,
              
              { transaction }
            );
        }
        
        if (data.trade_rule !== undefined) {
            await trade_rule_checks.setTrade_rule(
              
              data.trade_rule,
              
              { transaction }
            );
        }
        

        
        

        

        return trade_rule_checks;
    }

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

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

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


        return trade_rule_checks;
    }

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

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

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

        await trade_rule_checks.destroy({
            transaction
        });

        return trade_rule_checks;
    }

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

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

        if (!trade_rule_checks) {
            return trade_rule_checks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.trade = await trade_rule_checks.getTrade({
            transaction
        });
        
        
        output.trade_rule = await trade_rule_checks.getTrade_rule({
            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.trades,
        as: 'trade',
        
        where: filter.trade ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trade.split('|').map(term => Utils.uuid(term)) } },
            {
              notes: {
                [Op.or]: filter.trade.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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


      

      



            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_rule_checks.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_rule_checks',
                        'comment',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

