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

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

        const paper_orders = await db.paper_orders.create(
            {
                id: data.id || undefined,
        
        placed_at: data.placed_at
        ||
        null
            ,
            
        filled_at: data.filled_at
        ||
        null
            ,
            
        side: data.side
        ||
        null
            ,
            
        order_type: data.order_type
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        limit_price: data.limit_price
        ||
        null
            ,
            
        stop_price: data.stop_price
        ||
        null
            ,
            
        filled_quantity: data.filled_quantity
        ||
        null
            ,
            
        average_fill_price: data.average_fill_price
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        rejection_reason: data.rejection_reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await paper_orders.setPaper_account( data.paper_account || null, {
            transaction,
        });
        
        await paper_orders.setMarket_symbol( data.market_symbol || null, {
            transaction,
        });
        

        

        

        return paper_orders;
    }
    

    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 paper_ordersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                placed_at: item.placed_at
            ||
            null
            ,
            
                filled_at: item.filled_at
            ||
            null
            ,
            
                side: item.side
            ||
            null
            ,
            
                order_type: item.order_type
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                limit_price: item.limit_price
            ||
            null
            ,
            
                stop_price: item.stop_price
            ||
            null
            ,
            
                filled_quantity: item.filled_quantity
            ||
            null
            ,
            
                average_fill_price: item.average_fill_price
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                rejection_reason: item.rejection_reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return paper_orders;
    }

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

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


        

        const updatePayload = {};
        
        if (data.placed_at !== undefined) updatePayload.placed_at = data.placed_at;
        
        
        if (data.filled_at !== undefined) updatePayload.filled_at = data.filled_at;
        
        
        if (data.side !== undefined) updatePayload.side = data.side;
        
        
        if (data.order_type !== undefined) updatePayload.order_type = data.order_type;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.limit_price !== undefined) updatePayload.limit_price = data.limit_price;
        
        
        if (data.stop_price !== undefined) updatePayload.stop_price = data.stop_price;
        
        
        if (data.filled_quantity !== undefined) updatePayload.filled_quantity = data.filled_quantity;
        
        
        if (data.average_fill_price !== undefined) updatePayload.average_fill_price = data.average_fill_price;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.rejection_reason !== undefined) updatePayload.rejection_reason = data.rejection_reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.paper_account !== undefined) {
            await paper_orders.setPaper_account(
              
              data.paper_account,
              
              { transaction }
            );
        }
        
        if (data.market_symbol !== undefined) {
            await paper_orders.setMarket_symbol(
              
              data.market_symbol,
              
              { transaction }
            );
        }
        

        
        

        

        return paper_orders;
    }

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

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

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


        return paper_orders;
    }

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

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

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

        await paper_orders.destroy({
            transaction
        });

        return paper_orders;
    }

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

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

        if (!paper_orders) {
            return paper_orders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.paper_trades_paper_order = await paper_orders.getPaper_trades_paper_order({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.paper_account = await paper_orders.getPaper_account({
            transaction
        });
        
        
        output.market_symbol = await paper_orders.getMarket_symbol({
            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.paper_accounts,
        as: 'paper_account',
        
        where: filter.paper_account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.paper_account.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.paper_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.side) {
                where = {
                    ...where,
                side: filter.side,
            };
            }
            
            if (filter.order_type) {
                where = {
                    ...where,
                order_type: filter.order_type,
            };
            }
            
            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.paper_orders.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(
                        'paper_orders',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

