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

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

        const paper_positions = await db.paper_positions.create(
            {
                id: data.id || undefined,
        
        quantity: data.quantity
        ||
        null
            ,
            
        average_cost: data.average_cost
        ||
        null
            ,
            
        market_value: data.market_value
        ||
        null
            ,
            
        unrealized_pl: data.unrealized_pl
        ||
        null
            ,
            
        realized_pl: data.realized_pl
        ||
        null
            ,
            
        day_pl: data.day_pl
        ||
        null
            ,
            
        last_priced_at: data.last_priced_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return paper_positions;
    }
    

    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_positionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quantity: item.quantity
            ||
            null
            ,
            
                average_cost: item.average_cost
            ||
            null
            ,
            
                market_value: item.market_value
            ||
            null
            ,
            
                unrealized_pl: item.unrealized_pl
            ||
            null
            ,
            
                realized_pl: item.realized_pl
            ||
            null
            ,
            
                day_pl: item.day_pl
            ||
            null
            ,
            
                last_priced_at: item.last_priced_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return paper_positions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.average_cost !== undefined) updatePayload.average_cost = data.average_cost;
        
        
        if (data.market_value !== undefined) updatePayload.market_value = data.market_value;
        
        
        if (data.unrealized_pl !== undefined) updatePayload.unrealized_pl = data.unrealized_pl;
        
        
        if (data.realized_pl !== undefined) updatePayload.realized_pl = data.realized_pl;
        
        
        if (data.day_pl !== undefined) updatePayload.day_pl = data.day_pl;
        
        
        if (data.last_priced_at !== undefined) updatePayload.last_priced_at = data.last_priced_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return paper_positions;
    }

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

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

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


        return paper_positions;
    }

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

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

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

        await paper_positions.destroy({
            transaction
        });

        return paper_positions;
    }

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

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

        if (!paper_positions) {
            return paper_positions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.paper_account = await paper_positions.getPaper_account({
            transaction
        });
        
        
        output.market_symbol = await paper_positions.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.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.average_costRange) {
                const [start, end] = filter.average_costRange;

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    last_priced_at: {
                    ...where.last_priced_at,
                            [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_positions.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_positions',
                        'last_priced_at',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

