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

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

        const alert_rules = await db.alert_rules.create(
            {
                id: data.id || undefined,
        
        rule_type: data.rule_type
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
        threshold_value: data.threshold_value
        ||
        null
            ,
            
        threshold_unit: data.threshold_unit
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return alert_rules;
    }
    

    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 alert_rulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                rule_type: item.rule_type
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
                threshold_value: item.threshold_value
            ||
            null
            ,
            
                threshold_unit: item.threshold_unit
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return alert_rules;
    }

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

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


        

        const updatePayload = {};
        
        if (data.rule_type !== undefined) updatePayload.rule_type = data.rule_type;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        if (data.threshold_value !== undefined) updatePayload.threshold_value = data.threshold_value;
        
        
        if (data.threshold_unit !== undefined) updatePayload.threshold_unit = data.threshold_unit;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return alert_rules;
    }

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

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

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


        return alert_rules;
    }

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

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

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

        await alert_rules.destroy({
            transaction
        });

        return alert_rules;
    }

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

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

        if (!alert_rules) {
            return alert_rules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.alerts_alert_rule = await alert_rules.getAlerts_alert_rule({
            transaction
        });
        
        
        
        
        
        output.trading_account = await alert_rules.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.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alert_rules',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.rule_type) {
                where = {
                    ...where,
                rule_type: filter.rule_type,
            };
            }
            
            if (filter.is_enabled) {
                where = {
                    ...where,
                is_enabled: filter.is_enabled,
            };
            }
            
            if (filter.threshold_unit) {
                where = {
                    ...where,
                threshold_unit: filter.threshold_unit,
            };
            }
            


      



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

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

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

    
};

