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

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

        const screener_filters = await db.screener_filters.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        asset_class: data.asset_class
        ||
        null
            ,
            
        sector: data.sector
        ||
        null
            ,
            
        market_cap_min: data.market_cap_min
        ||
        null
            ,
            
        market_cap_max: data.market_cap_max
        ||
        null
            ,
            
        pe_min: data.pe_min
        ||
        null
            ,
            
        pe_max: data.pe_max
        ||
        null
            ,
            
        price_min: data.price_min
        ||
        null
            ,
            
        price_max: data.price_max
        ||
        null
            ,
            
        volume_min: data.volume_min
        ||
        null
            ,
            
        performance_52w_min: data.performance_52w_min
        ||
        null
            ,
            
        performance_52w_max: data.performance_52w_max
        ||
        null
            ,
            
        is_pinned: data.is_pinned
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await screener_filters.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return screener_filters;
    }
    

    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_filtersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                asset_class: item.asset_class
            ||
            null
            ,
            
                sector: item.sector
            ||
            null
            ,
            
                market_cap_min: item.market_cap_min
            ||
            null
            ,
            
                market_cap_max: item.market_cap_max
            ||
            null
            ,
            
                pe_min: item.pe_min
            ||
            null
            ,
            
                pe_max: item.pe_max
            ||
            null
            ,
            
                price_min: item.price_min
            ||
            null
            ,
            
                price_max: item.price_max
            ||
            null
            ,
            
                volume_min: item.volume_min
            ||
            null
            ,
            
                performance_52w_min: item.performance_52w_min
            ||
            null
            ,
            
                performance_52w_max: item.performance_52w_max
            ||
            null
            ,
            
                is_pinned: item.is_pinned
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return screener_filters;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.asset_class !== undefined) updatePayload.asset_class = data.asset_class;
        
        
        if (data.sector !== undefined) updatePayload.sector = data.sector;
        
        
        if (data.market_cap_min !== undefined) updatePayload.market_cap_min = data.market_cap_min;
        
        
        if (data.market_cap_max !== undefined) updatePayload.market_cap_max = data.market_cap_max;
        
        
        if (data.pe_min !== undefined) updatePayload.pe_min = data.pe_min;
        
        
        if (data.pe_max !== undefined) updatePayload.pe_max = data.pe_max;
        
        
        if (data.price_min !== undefined) updatePayload.price_min = data.price_min;
        
        
        if (data.price_max !== undefined) updatePayload.price_max = data.price_max;
        
        
        if (data.volume_min !== undefined) updatePayload.volume_min = data.volume_min;
        
        
        if (data.performance_52w_min !== undefined) updatePayload.performance_52w_min = data.performance_52w_min;
        
        
        if (data.performance_52w_max !== undefined) updatePayload.performance_52w_max = data.performance_52w_max;
        
        
        if (data.is_pinned !== undefined) updatePayload.is_pinned = data.is_pinned;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await screener_filters.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return screener_filters;
    }

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

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

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


        return screener_filters;
    }

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

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

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

        await screener_filters.destroy({
            transaction
        });

        return screener_filters;
    }

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

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

        if (!screener_filters) {
            return screener_filters;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.screener_runs_screener_filter = await screener_filters.getScreener_runs_screener_filter({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await screener_filters.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'screener_filters',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.sector) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'screener_filters',
                        'sector',
                        filter.sector,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    performance_52w_max: {
                    ...where.performance_52w_max,
                            [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.is_pinned) {
                where = {
                    ...where,
                is_pinned: filter.is_pinned,
            };
            }
            


      



            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_filters.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_filters',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

