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

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

        const technical_indicators = await db.technical_indicators.create(
            {
                id: data.id || undefined,
        
        calculated_at: data.calculated_at
        ||
        null
            ,
            
        indicator_type: data.indicator_type
        ||
        null
            ,
            
        timeframe: data.timeframe
        ||
        null
            ,
            
        period: data.period
        ||
        null
            ,
            
        value: data.value
        ||
        null
            ,
            
        signal: data.signal
        ||
        null
            ,
            
        histogram: data.histogram
        ||
        null
            ,
            
        upper_band: data.upper_band
        ||
        null
            ,
            
        middle_band: data.middle_band
        ||
        null
            ,
            
        lower_band: data.lower_band
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return technical_indicators;
    }
    

    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 technical_indicatorsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                calculated_at: item.calculated_at
            ||
            null
            ,
            
                indicator_type: item.indicator_type
            ||
            null
            ,
            
                timeframe: item.timeframe
            ||
            null
            ,
            
                period: item.period
            ||
            null
            ,
            
                value: item.value
            ||
            null
            ,
            
                signal: item.signal
            ||
            null
            ,
            
                histogram: item.histogram
            ||
            null
            ,
            
                upper_band: item.upper_band
            ||
            null
            ,
            
                middle_band: item.middle_band
            ||
            null
            ,
            
                lower_band: item.lower_band
            ||
            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 technical_indicators = await db.technical_indicators.bulkCreate(technical_indicatorsData, { transaction });

        // For each item created, replace relation files
        

        return technical_indicators;
    }

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

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


        

        const updatePayload = {};
        
        if (data.calculated_at !== undefined) updatePayload.calculated_at = data.calculated_at;
        
        
        if (data.indicator_type !== undefined) updatePayload.indicator_type = data.indicator_type;
        
        
        if (data.timeframe !== undefined) updatePayload.timeframe = data.timeframe;
        
        
        if (data.period !== undefined) updatePayload.period = data.period;
        
        
        if (data.value !== undefined) updatePayload.value = data.value;
        
        
        if (data.signal !== undefined) updatePayload.signal = data.signal;
        
        
        if (data.histogram !== undefined) updatePayload.histogram = data.histogram;
        
        
        if (data.upper_band !== undefined) updatePayload.upper_band = data.upper_band;
        
        
        if (data.middle_band !== undefined) updatePayload.middle_band = data.middle_band;
        
        
        if (data.lower_band !== undefined) updatePayload.lower_band = data.lower_band;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return technical_indicators;
    }

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

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

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


        return technical_indicators;
    }

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

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

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

        await technical_indicators.destroy({
            transaction
        });

        return technical_indicators;
    }

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

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

        if (!technical_indicators) {
            return technical_indicators;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.market_symbol = await technical_indicators.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(
                        'technical_indicators',
                        'source',
                        filter.source,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      



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

        const records = await db.technical_indicators.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,
        }));
    }

    
};

