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

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

        const symbol_fundamentals = await db.symbol_fundamentals.create(
            {
                id: data.id || undefined,
        
        pe_ratio: data.pe_ratio
        ||
        null
            ,
            
        eps: data.eps
        ||
        null
            ,
            
        market_cap: data.market_cap
        ||
        null
            ,
            
        revenue: data.revenue
        ||
        null
            ,
            
        dividend_yield: data.dividend_yield
        ||
        null
            ,
            
        beta: data.beta
        ||
        null
            ,
            
        shares_outstanding: data.shares_outstanding
        ||
        null
            ,
            
        as_of_at: data.as_of_at
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await symbol_fundamentals.setMarket_symbol( data.market_symbol || null, {
            transaction,
        });
        

        

        

        return symbol_fundamentals;
    }
    

    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 symbol_fundamentalsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                pe_ratio: item.pe_ratio
            ||
            null
            ,
            
                eps: item.eps
            ||
            null
            ,
            
                market_cap: item.market_cap
            ||
            null
            ,
            
                revenue: item.revenue
            ||
            null
            ,
            
                dividend_yield: item.dividend_yield
            ||
            null
            ,
            
                beta: item.beta
            ||
            null
            ,
            
                shares_outstanding: item.shares_outstanding
            ||
            null
            ,
            
                as_of_at: item.as_of_at
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return symbol_fundamentals;
    }

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

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


        

        const updatePayload = {};
        
        if (data.pe_ratio !== undefined) updatePayload.pe_ratio = data.pe_ratio;
        
        
        if (data.eps !== undefined) updatePayload.eps = data.eps;
        
        
        if (data.market_cap !== undefined) updatePayload.market_cap = data.market_cap;
        
        
        if (data.revenue !== undefined) updatePayload.revenue = data.revenue;
        
        
        if (data.dividend_yield !== undefined) updatePayload.dividend_yield = data.dividend_yield;
        
        
        if (data.beta !== undefined) updatePayload.beta = data.beta;
        
        
        if (data.shares_outstanding !== undefined) updatePayload.shares_outstanding = data.shares_outstanding;
        
        
        if (data.as_of_at !== undefined) updatePayload.as_of_at = data.as_of_at;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return symbol_fundamentals;
    }

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

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

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


        return symbol_fundamentals;
    }

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

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

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

        await symbol_fundamentals.destroy({
            transaction
        });

        return symbol_fundamentals;
    }

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

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

        if (!symbol_fundamentals) {
            return symbol_fundamentals;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.market_symbol = await symbol_fundamentals.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.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.source) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'symbol_fundamentals',
                        'source',
                        filter.source,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    as_of_at: {
                    ...where.as_of_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.symbol_fundamentals.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(
                        'symbol_fundamentals',
                        'source',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

