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

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

        const paper_accounts = await db.paper_accounts.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        base_currency: data.base_currency
        ||
        null
            ,
            
        starting_cash: data.starting_cash
        ||
        null
            ,
            
        cash_balance: data.cash_balance
        ||
        null
            ,
            
        buying_power: data.buying_power
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        opened_at: data.opened_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return paper_accounts;
    }
    

    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 paper_accountsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                base_currency: item.base_currency
            ||
            null
            ,
            
                starting_cash: item.starting_cash
            ||
            null
            ,
            
                cash_balance: item.cash_balance
            ||
            null
            ,
            
                buying_power: item.buying_power
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                opened_at: item.opened_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return paper_accounts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.base_currency !== undefined) updatePayload.base_currency = data.base_currency;
        
        
        if (data.starting_cash !== undefined) updatePayload.starting_cash = data.starting_cash;
        
        
        if (data.cash_balance !== undefined) updatePayload.cash_balance = data.cash_balance;
        
        
        if (data.buying_power !== undefined) updatePayload.buying_power = data.buying_power;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return paper_accounts;
    }

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

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

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


        return paper_accounts;
    }

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

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

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

        await paper_accounts.destroy({
            transaction
        });

        return paper_accounts;
    }

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

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

        if (!paper_accounts) {
            return paper_accounts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.paper_orders_paper_account = await paper_accounts.getPaper_orders_paper_account({
            transaction
        });
        
        
        
        output.paper_positions_paper_account = await paper_accounts.getPaper_positions_paper_account({
            transaction
        });
        
        
        output.portfolio_snapshots_paper_account = await paper_accounts.getPortfolio_snapshots_paper_account({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await paper_accounts.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(
                        'paper_accounts',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.base_currency) {
                where = {
                    ...where,
                base_currency: filter.base_currency,
            };
            }
            
            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.paper_accounts.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(
                        'paper_accounts',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

    
};

