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

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

        const market_symbols = await db.market_symbols.create(
            {
                id: data.id || undefined,
        
        symbol: data.symbol
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        asset_class: data.asset_class
        ||
        null
            ,
            
        exchange: data.exchange
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        sector: data.sector
        ||
        null
            ,
            
        industry: data.industry
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
        last_refreshed_at: data.last_refreshed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return market_symbols;
    }
    

    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 market_symbolsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                symbol: item.symbol
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                asset_class: item.asset_class
            ||
            null
            ,
            
                exchange: item.exchange
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                sector: item.sector
            ||
            null
            ,
            
                industry: item.industry
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
                last_refreshed_at: item.last_refreshed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return market_symbols;
    }

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

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


        

        const updatePayload = {};
        
        if (data.symbol !== undefined) updatePayload.symbol = data.symbol;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.asset_class !== undefined) updatePayload.asset_class = data.asset_class;
        
        
        if (data.exchange !== undefined) updatePayload.exchange = data.exchange;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.sector !== undefined) updatePayload.sector = data.sector;
        
        
        if (data.industry !== undefined) updatePayload.industry = data.industry;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        if (data.last_refreshed_at !== undefined) updatePayload.last_refreshed_at = data.last_refreshed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return market_symbols;
    }

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

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

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


        return market_symbols;
    }

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

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

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

        await market_symbols.destroy({
            transaction
        });

        return market_symbols;
    }

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

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

        if (!market_symbols) {
            return market_symbols;
        }

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

        
        
        
        
        
        
        output.symbol_fundamentals_market_symbol = await market_symbols.getSymbol_fundamentals_market_symbol({
            transaction
        });
        
        
        output.price_quotes_market_symbol = await market_symbols.getPrice_quotes_market_symbol({
            transaction
        });
        
        
        output.technical_indicators_market_symbol = await market_symbols.getTechnical_indicators_market_symbol({
            transaction
        });
        
        
        output.analyst_ratings_market_symbol = await market_symbols.getAnalyst_ratings_market_symbol({
            transaction
        });
        
        
        output.earnings_reports_market_symbol = await market_symbols.getEarnings_reports_market_symbol({
            transaction
        });
        
        
        
        output.news_article_symbols_market_symbol = await market_symbols.getNews_article_symbols_market_symbol({
            transaction
        });
        
        
        
        
        output.watchlist_items_market_symbol = await market_symbols.getWatchlist_items_market_symbol({
            transaction
        });
        
        
        
        output.paper_orders_market_symbol = await market_symbols.getPaper_orders_market_symbol({
            transaction
        });
        
        
        
        output.paper_positions_market_symbol = await market_symbols.getPaper_positions_market_symbol({
            transaction
        });
        
        
        
        
        
        output.screener_results_market_symbol = await market_symbols.getScreener_results_market_symbol({
            transaction
        });
        
        
        
        
        
        
        output.ir_companies_market_symbol = await market_symbols.getIr_companies_market_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 = [



    ];

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

            
            if (filter.symbol) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'market_symbols',
                        'symbol',
                        filter.symbol,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'market_symbols',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.exchange) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'market_symbols',
                        'exchange',
                        filter.exchange,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'market_symbols',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'market_symbols',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.sector) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'market_symbols',
                        'sector',
                        filter.sector,
                    ),
                };
            }
            
            if (filter.industry) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'market_symbols',
                        'industry',
                        filter.industry,
                    ),
                };
            }
            

            
            

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

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

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

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

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




            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.market_symbols.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(
                        'market_symbols',
                        'symbol',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

