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

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

        const paper_trades = await db.paper_trades.create(
            {
                id: data.id || undefined,
        
        executed_at: data.executed_at
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        fees: data.fees
        ||
        null
            ,
            
        venue: data.venue
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await paper_trades.setPaper_order( data.paper_order || null, {
            transaction,
        });
        

        

        

        return paper_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 paper_tradesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                executed_at: item.executed_at
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                fees: item.fees
            ||
            null
            ,
            
                venue: item.venue
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return paper_trades;
    }

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

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


        

        const updatePayload = {};
        
        if (data.executed_at !== undefined) updatePayload.executed_at = data.executed_at;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.fees !== undefined) updatePayload.fees = data.fees;
        
        
        if (data.venue !== undefined) updatePayload.venue = data.venue;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.paper_order !== undefined) {
            await paper_trades.setPaper_order(
              
              data.paper_order,
              
              { transaction }
            );
        }
        

        
        

        

        return paper_trades;
    }

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

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

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


        return paper_trades;
    }

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

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

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

        await paper_trades.destroy({
            transaction
        });

        return paper_trades;
    }

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

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

        if (!paper_trades) {
            return paper_trades;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.paper_order = await paper_trades.getPaper_order({
            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_orders,
        as: 'paper_order',
        
        where: filter.paper_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.paper_order.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.paper_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    executed_at: {
                    ...where.executed_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.priceRange) {
                const [start, end] = filter.priceRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    price: {
                    ...where.price,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            


      



            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_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(
                        'paper_trades',
                        'venue',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

