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

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

        const investment_positions = await db.investment_positions.create(
            {
                id: data.id || undefined,
        
        ticker: data.ticker
        ||
        null
            ,
            
        asset_name: data.asset_name
        ||
        null
            ,
            
        asset_type: data.asset_type
        ||
        null
            ,
            
        brokerage_name: data.brokerage_name
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        avg_cost: data.avg_cost
        ||
        null
            ,
            
        value_previous_year: data.value_previous_year
        ||
        null
            ,
            
        value_current_year: data.value_current_year
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await investment_positions.setDeclaration( data.declaration || null, {
            transaction,
        });
        
        await investment_positions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return investment_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 investment_positionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                ticker: item.ticker
            ||
            null
            ,
            
                asset_name: item.asset_name
            ||
            null
            ,
            
                asset_type: item.asset_type
            ||
            null
            ,
            
                brokerage_name: item.brokerage_name
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                avg_cost: item.avg_cost
            ||
            null
            ,
            
                value_previous_year: item.value_previous_year
            ||
            null
            ,
            
                value_current_year: item.value_current_year
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return investment_positions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.ticker !== undefined) updatePayload.ticker = data.ticker;
        
        
        if (data.asset_name !== undefined) updatePayload.asset_name = data.asset_name;
        
        
        if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
        
        
        if (data.brokerage_name !== undefined) updatePayload.brokerage_name = data.brokerage_name;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.avg_cost !== undefined) updatePayload.avg_cost = data.avg_cost;
        
        
        if (data.value_previous_year !== undefined) updatePayload.value_previous_year = data.value_previous_year;
        
        
        if (data.value_current_year !== undefined) updatePayload.value_current_year = data.value_current_year;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.declaration !== undefined) {
            await investment_positions.setDeclaration(
              
              data.declaration,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await investment_positions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return investment_positions;
    }

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

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

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


        return investment_positions;
    }

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

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

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

        await investment_positions.destroy({
            transaction
        });

        return investment_positions;
    }

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

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

        if (!investment_positions) {
            return investment_positions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.declaration = await investment_positions.getDeclaration({
            transaction
        });
        
        
        output.organizations = await investment_positions.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.ticker) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'investment_positions',
                        'ticker',
                        filter.ticker,
                    ),
                };
            }
            
            if (filter.asset_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'investment_positions',
                        'asset_name',
                        filter.asset_name,
                    ),
                };
            }
            
            if (filter.brokerage_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'investment_positions',
                        'brokerage_name',
                        filter.brokerage_name,
                    ),
                };
            }
            

            
            

            
            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.avg_costRange) {
                const [start, end] = filter.avg_costRange;

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

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

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

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

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

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

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

            
            if (filter.asset_type) {
                where = {
                    ...where,
                asset_type: filter.asset_type,
            };
            }
            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.investment_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'investment_positions',
                        'ticker',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

