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

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

        const trading_accounts = await db.trading_accounts.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        broker_name: data.broker_name
        ||
        null
            ,
            
        base_currency: data.base_currency
        ||
        null
            ,
            
        starting_balance: data.starting_balance
        ||
        null
            ,
            
        current_balance: data.current_balance
        ||
        null
            ,
            
        risk_per_trade_default: data.risk_per_trade_default
        ||
        null
            ,
            
        risk_unit: data.risk_unit
        ||
        null
            ,
            
        is_archived: data.is_archived
        ||
        false
        
            ,
            
        opened_at: data.opened_at
        ||
        null
            ,
            
        archived_at: data.archived_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trading_accounts.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return trading_accounts;
    }
    

    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 trading_accountsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                broker_name: item.broker_name
            ||
            null
            ,
            
                base_currency: item.base_currency
            ||
            null
            ,
            
                starting_balance: item.starting_balance
            ||
            null
            ,
            
                current_balance: item.current_balance
            ||
            null
            ,
            
                risk_per_trade_default: item.risk_per_trade_default
            ||
            null
            ,
            
                risk_unit: item.risk_unit
            ||
            null
            ,
            
                is_archived: item.is_archived
            ||
            false
        
            ,
            
                opened_at: item.opened_at
            ||
            null
            ,
            
                archived_at: item.archived_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trading_accounts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.broker_name !== undefined) updatePayload.broker_name = data.broker_name;
        
        
        if (data.base_currency !== undefined) updatePayload.base_currency = data.base_currency;
        
        
        if (data.starting_balance !== undefined) updatePayload.starting_balance = data.starting_balance;
        
        
        if (data.current_balance !== undefined) updatePayload.current_balance = data.current_balance;
        
        
        if (data.risk_per_trade_default !== undefined) updatePayload.risk_per_trade_default = data.risk_per_trade_default;
        
        
        if (data.risk_unit !== undefined) updatePayload.risk_unit = data.risk_unit;
        
        
        if (data.is_archived !== undefined) updatePayload.is_archived = data.is_archived;
        
        
        if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
        
        
        if (data.archived_at !== undefined) updatePayload.archived_at = data.archived_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await trading_accounts.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return trading_accounts;
    }

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

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

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


        return trading_accounts;
    }

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

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

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

        await trading_accounts.destroy({
            transaction
        });

        return trading_accounts;
    }

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

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

        if (!trading_accounts) {
            return trading_accounts;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.trades_trading_account = await trading_accounts.getTrades_trading_account({
            transaction
        });
        
        
        
        
        
        
        output.goals_trading_account = await trading_accounts.getGoals_trading_account({
            transaction
        });
        
        
        
        
        
        output.csv_import_jobs_trading_account = await trading_accounts.getCsv_import_jobs_trading_account({
            transaction
        });
        
        
        
        output.broker_connections_trading_account = await trading_accounts.getBroker_connections_trading_account({
            transaction
        });
        
        
        
        output.ai_insight_runs_trading_account = await trading_accounts.getAi_insight_runs_trading_account({
            transaction
        });
        
        
        
        output.alert_rules_trading_account = await trading_accounts.getAlert_rules_trading_account({
            transaction
        });
        
        
        
        
        output.pdf_reports_trading_account = await trading_accounts.getPdf_reports_trading_account({
            transaction
        });
        
        
        
        output.user = await trading_accounts.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trading_accounts',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.broker_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trading_accounts',
                        'broker_name',
                        filter.broker_name,
                    ),
                };
            }
            
            if (filter.base_currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trading_accounts',
                        'base_currency',
                        filter.base_currency,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

