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

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

        const portfolio_snapshots = await db.portfolio_snapshots.create(
            {
                id: data.id || undefined,
        
        snapshotted_at: data.snapshotted_at
        ||
        null
            ,
            
        total_value: data.total_value
        ||
        null
            ,
            
        cash_value: data.cash_value
        ||
        null
            ,
            
        positions_value: data.positions_value
        ||
        null
            ,
            
        day_pl: data.day_pl
        ||
        null
            ,
            
        all_time_pl: data.all_time_pl
        ||
        null
            ,
            
        day_pl_percent: data.day_pl_percent
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await portfolio_snapshots.setPaper_account( data.paper_account || null, {
            transaction,
        });
        

        

        

        return portfolio_snapshots;
    }
    

    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 portfolio_snapshotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                snapshotted_at: item.snapshotted_at
            ||
            null
            ,
            
                total_value: item.total_value
            ||
            null
            ,
            
                cash_value: item.cash_value
            ||
            null
            ,
            
                positions_value: item.positions_value
            ||
            null
            ,
            
                day_pl: item.day_pl
            ||
            null
            ,
            
                all_time_pl: item.all_time_pl
            ||
            null
            ,
            
                day_pl_percent: item.day_pl_percent
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return portfolio_snapshots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.snapshotted_at !== undefined) updatePayload.snapshotted_at = data.snapshotted_at;
        
        
        if (data.total_value !== undefined) updatePayload.total_value = data.total_value;
        
        
        if (data.cash_value !== undefined) updatePayload.cash_value = data.cash_value;
        
        
        if (data.positions_value !== undefined) updatePayload.positions_value = data.positions_value;
        
        
        if (data.day_pl !== undefined) updatePayload.day_pl = data.day_pl;
        
        
        if (data.all_time_pl !== undefined) updatePayload.all_time_pl = data.all_time_pl;
        
        
        if (data.day_pl_percent !== undefined) updatePayload.day_pl_percent = data.day_pl_percent;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return portfolio_snapshots;
    }

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

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

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


        return portfolio_snapshots;
    }

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

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

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

        await portfolio_snapshots.destroy({
            transaction
        });

        return portfolio_snapshots;
    }

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

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

        if (!portfolio_snapshots) {
            return portfolio_snapshots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.paper_account = await portfolio_snapshots.getPaper_account({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
};

