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

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

        const instruments = await db.instruments.create(
            {
                id: data.id || undefined,
        
        symbol: data.symbol
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        asset_class: data.asset_class
        ||
        null
            ,
            
        exchange: data.exchange
        ||
        null
            ,
            
        tick_size: data.tick_size
        ||
        null
            ,
            
        pip_value_hint: data.pip_value_hint
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return instruments;
    }
    

    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 instrumentsData = 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
            ,
            
                tick_size: item.tick_size
            ||
            null
            ,
            
                pip_value_hint: item.pip_value_hint
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return instruments;
    }

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

        const instruments = await db.instruments.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.tick_size !== undefined) updatePayload.tick_size = data.tick_size;
        
        
        if (data.pip_value_hint !== undefined) updatePayload.pip_value_hint = data.pip_value_hint;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return instruments;
    }

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

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

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


        return instruments;
    }

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

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

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

        await instruments.destroy({
            transaction
        });

        return instruments;
    }

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

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

        if (!instruments) {
            return instruments;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.trades_instrument = await instruments.getTrades_instrument({
            transaction
        });
        
        
        
        
        
        
        
        
        output.watchlist_items_instrument = await instruments.getWatchlist_items_instrument({
            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(
                        'instruments',
                        'symbol',
                        filter.symbol,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'instruments',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.exchange) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'instruments',
                        'exchange',
                        filter.exchange,
                    ),
                };
            }
            
            if (filter.tick_size) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'instruments',
                        'tick_size',
                        filter.tick_size,
                    ),
                };
            }
            
            if (filter.pip_value_hint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'instruments',
                        'pip_value_hint',
                        filter.pip_value_hint,
                    ),
                };
            }
            

            
            

            

            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_active) {
                where = {
                    ...where,
                is_active: filter.is_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.instruments.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(
                        'instruments',
                        'symbol',
                        query,
                    ),
                ],
            };
        }

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

    
};

