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

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

        const price_quotes = await db.price_quotes.create(
            {
                id: data.id || undefined,
        
        quoted_at: data.quoted_at
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        open: data.open
        ||
        null
            ,
            
        high: data.high
        ||
        null
            ,
            
        low: data.low
        ||
        null
            ,
            
        previous_close: data.previous_close
        ||
        null
            ,
            
        change_amount: data.change_amount
        ||
        null
            ,
            
        change_percent: data.change_percent
        ||
        null
            ,
            
        volume: data.volume
        ||
        null
            ,
            
        timeframe: data.timeframe
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return price_quotes;
    }
    

    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 price_quotesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quoted_at: item.quoted_at
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                open: item.open
            ||
            null
            ,
            
                high: item.high
            ||
            null
            ,
            
                low: item.low
            ||
            null
            ,
            
                previous_close: item.previous_close
            ||
            null
            ,
            
                change_amount: item.change_amount
            ||
            null
            ,
            
                change_percent: item.change_percent
            ||
            null
            ,
            
                volume: item.volume
            ||
            null
            ,
            
                timeframe: item.timeframe
            ||
            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 price_quotes = await db.price_quotes.bulkCreate(price_quotesData, { transaction });

        // For each item created, replace relation files
        

        return price_quotes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quoted_at !== undefined) updatePayload.quoted_at = data.quoted_at;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.open !== undefined) updatePayload.open = data.open;
        
        
        if (data.high !== undefined) updatePayload.high = data.high;
        
        
        if (data.low !== undefined) updatePayload.low = data.low;
        
        
        if (data.previous_close !== undefined) updatePayload.previous_close = data.previous_close;
        
        
        if (data.change_amount !== undefined) updatePayload.change_amount = data.change_amount;
        
        
        if (data.change_percent !== undefined) updatePayload.change_percent = data.change_percent;
        
        
        if (data.volume !== undefined) updatePayload.volume = data.volume;
        
        
        if (data.timeframe !== undefined) updatePayload.timeframe = data.timeframe;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return price_quotes;
    }

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

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

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


        return price_quotes;
    }

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

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

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

        await price_quotes.destroy({
            transaction
        });

        return price_quotes;
    }

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

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

        if (!price_quotes) {
            return price_quotes;
        }

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
};

