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

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

        const trades = await db.trades.create(
            {
                id: data.id || undefined,
        
        direction: data.direction
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        timeframe: data.timeframe
        ||
        null
            ,
            
        entry_at: data.entry_at
        ||
        null
            ,
            
        exit_at: data.exit_at
        ||
        null
            ,
            
        entry_price: data.entry_price
        ||
        null
            ,
            
        exit_price: data.exit_price
        ||
        null
            ,
            
        stop_loss_price: data.stop_loss_price
        ||
        null
            ,
            
        take_profit_price: data.take_profit_price
        ||
        null
            ,
            
        position_size: data.position_size
        ||
        null
            ,
            
        position_size_unit: data.position_size_unit
        ||
        null
            ,
            
        fees: data.fees
        ||
        null
            ,
            
        slippage: data.slippage
        ||
        null
            ,
            
        pnl_amount: data.pnl_amount
        ||
        null
            ,
            
        pnl_percent: data.pnl_percent
        ||
        null
            ,
            
        risk_amount: data.risk_amount
        ||
        null
            ,
            
        rr_ratio: data.rr_ratio
        ||
        null
            ,
            
        mae_amount: data.mae_amount
        ||
        null
            ,
            
        mfe_amount: data.mfe_amount
        ||
        null
            ,
            
        duration_minutes: data.duration_minutes
        ||
        null
            ,
            
        is_win: data.is_win
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trades.setTrading_account( data.trading_account || null, {
            transaction,
        });
        
        await trades.setInstrument( data.instrument || null, {
            transaction,
        });
        
        await trades.setSetup( data.setup || null, {
            transaction,
        });
        

        
        await trades.setTags(data.tags || [], {
            transaction,
        });
        

        

        return trades;
    }
    

    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 tradesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                direction: item.direction
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                timeframe: item.timeframe
            ||
            null
            ,
            
                entry_at: item.entry_at
            ||
            null
            ,
            
                exit_at: item.exit_at
            ||
            null
            ,
            
                entry_price: item.entry_price
            ||
            null
            ,
            
                exit_price: item.exit_price
            ||
            null
            ,
            
                stop_loss_price: item.stop_loss_price
            ||
            null
            ,
            
                take_profit_price: item.take_profit_price
            ||
            null
            ,
            
                position_size: item.position_size
            ||
            null
            ,
            
                position_size_unit: item.position_size_unit
            ||
            null
            ,
            
                fees: item.fees
            ||
            null
            ,
            
                slippage: item.slippage
            ||
            null
            ,
            
                pnl_amount: item.pnl_amount
            ||
            null
            ,
            
                pnl_percent: item.pnl_percent
            ||
            null
            ,
            
                risk_amount: item.risk_amount
            ||
            null
            ,
            
                rr_ratio: item.rr_ratio
            ||
            null
            ,
            
                mae_amount: item.mae_amount
            ||
            null
            ,
            
                mfe_amount: item.mfe_amount
            ||
            null
            ,
            
                duration_minutes: item.duration_minutes
            ||
            null
            ,
            
                is_win: item.is_win
            ||
            false
        
            ,
            
                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 trades = await db.trades.bulkCreate(tradesData, { transaction });

        // For each item created, replace relation files
        

        return trades;
    }

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

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


        

        const updatePayload = {};
        
        if (data.direction !== undefined) updatePayload.direction = data.direction;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.timeframe !== undefined) updatePayload.timeframe = data.timeframe;
        
        
        if (data.entry_at !== undefined) updatePayload.entry_at = data.entry_at;
        
        
        if (data.exit_at !== undefined) updatePayload.exit_at = data.exit_at;
        
        
        if (data.entry_price !== undefined) updatePayload.entry_price = data.entry_price;
        
        
        if (data.exit_price !== undefined) updatePayload.exit_price = data.exit_price;
        
        
        if (data.stop_loss_price !== undefined) updatePayload.stop_loss_price = data.stop_loss_price;
        
        
        if (data.take_profit_price !== undefined) updatePayload.take_profit_price = data.take_profit_price;
        
        
        if (data.position_size !== undefined) updatePayload.position_size = data.position_size;
        
        
        if (data.position_size_unit !== undefined) updatePayload.position_size_unit = data.position_size_unit;
        
        
        if (data.fees !== undefined) updatePayload.fees = data.fees;
        
        
        if (data.slippage !== undefined) updatePayload.slippage = data.slippage;
        
        
        if (data.pnl_amount !== undefined) updatePayload.pnl_amount = data.pnl_amount;
        
        
        if (data.pnl_percent !== undefined) updatePayload.pnl_percent = data.pnl_percent;
        
        
        if (data.risk_amount !== undefined) updatePayload.risk_amount = data.risk_amount;
        
        
        if (data.rr_ratio !== undefined) updatePayload.rr_ratio = data.rr_ratio;
        
        
        if (data.mae_amount !== undefined) updatePayload.mae_amount = data.mae_amount;
        
        
        if (data.mfe_amount !== undefined) updatePayload.mfe_amount = data.mfe_amount;
        
        
        if (data.duration_minutes !== undefined) updatePayload.duration_minutes = data.duration_minutes;
        
        
        if (data.is_win !== undefined) updatePayload.is_win = data.is_win;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trading_account !== undefined) {
            await trades.setTrading_account(
              
              data.trading_account,
              
              { transaction }
            );
        }
        
        if (data.instrument !== undefined) {
            await trades.setInstrument(
              
              data.instrument,
              
              { transaction }
            );
        }
        
        if (data.setup !== undefined) {
            await trades.setSetup(
              
              data.setup,
              
              { transaction }
            );
        }
        

        
        
        if (data.tags !== undefined) {
            await trades.setTags(data.tags, { transaction });
        }
        

        

        return trades;
    }

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

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

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


        return trades;
    }

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

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

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

        await trades.destroy({
            transaction
        });

        return trades;
    }

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

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

        if (!trades) {
            return trades;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.trade_attachments_trade = await trades.getTrade_attachments_trade({
            transaction
        });
        
        
        
        output.trade_rule_checks_trade = await trades.getTrade_rule_checks_trade({
            transaction
        });
        
        
        output.mood_entries_trade = await trades.getMood_entries_trade({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.alerts_trade = await trades.getAlerts_trade({
            transaction
        });
        
        
        
        
        
        output.trading_account = await trades.getTrading_account({
            transaction
        });
        
        
        output.instrument = await trades.getInstrument({
            transaction
        });
        
        
        output.setup = await trades.getSetup({
            transaction
        });
        
        
        output.tags = await trades.getTags({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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


      {
        model: db.tags,
        as: 'tags',
        required: false,
      },


    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            entry_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    exit_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.direction) {
                where = {
                    ...where,
                direction: filter.direction,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.timeframe) {
                where = {
                    ...where,
                timeframe: filter.timeframe,
            };
            }
            
            if (filter.position_size_unit) {
                where = {
                    ...where,
                position_size_unit: filter.position_size_unit,
            };
            }
            
            if (filter.is_win) {
                where = {
                    ...where,
                is_win: filter.is_win,
            };
            }
            


      

      

      


      if (filter.tags) {
        const searchTerms = filter.tags.split('|');

        include = [
          {
            model: db.tags,
            as: 'tags_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

        const records = await db.trades.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,
        }));
    }

    
};

