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

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

        const screener_results = await db.screener_results.create(
            {
                id: data.id || undefined,
        
        last_price: data.last_price
        ||
        null
            ,
            
        market_cap: data.market_cap
        ||
        null
            ,
            
        pe_ratio: data.pe_ratio
        ||
        null
            ,
            
        volume: data.volume
        ||
        null
            ,
            
        performance_52w: data.performance_52w
        ||
        null
            ,
            
        sector: data.sector
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await screener_results.setScreener_run( data.screener_run || null, {
            transaction,
        });
        
        await screener_results.setMarket_symbol( data.market_symbol || null, {
            transaction,
        });
        

        

        

        return screener_results;
    }
    

    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 screener_resultsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                last_price: item.last_price
            ||
            null
            ,
            
                market_cap: item.market_cap
            ||
            null
            ,
            
                pe_ratio: item.pe_ratio
            ||
            null
            ,
            
                volume: item.volume
            ||
            null
            ,
            
                performance_52w: item.performance_52w
            ||
            null
            ,
            
                sector: item.sector
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return screener_results;
    }

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

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


        

        const updatePayload = {};
        
        if (data.last_price !== undefined) updatePayload.last_price = data.last_price;
        
        
        if (data.market_cap !== undefined) updatePayload.market_cap = data.market_cap;
        
        
        if (data.pe_ratio !== undefined) updatePayload.pe_ratio = data.pe_ratio;
        
        
        if (data.volume !== undefined) updatePayload.volume = data.volume;
        
        
        if (data.performance_52w !== undefined) updatePayload.performance_52w = data.performance_52w;
        
        
        if (data.sector !== undefined) updatePayload.sector = data.sector;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return screener_results;
    }

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

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

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


        return screener_results;
    }

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

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

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

        await screener_results.destroy({
            transaction
        });

        return screener_results;
    }

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

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

        if (!screener_results) {
            return screener_results;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.screener_run = await screener_results.getScreener_run({
            transaction
        });
        
        
        output.market_symbol = await screener_results.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.screener_runs,
        as: 'screener_run',
        
        where: filter.screener_run ? {
          [Op.or]: [
            { id: { [Op.in]: filter.screener_run.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.screener_run.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.sector) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'screener_results',
                        'sector',
                        filter.sector,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

    
};

