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

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

        const metrics_snapshots = await db.metrics_snapshots.create(
            {
                id: data.id || undefined,
        
        as_of_at: data.as_of_at
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        cash_balance: data.cash_balance
        ||
        null
            ,
            
        net_burn_monthly: data.net_burn_monthly
        ||
        null
            ,
            
        gross_margin_percent: data.gross_margin_percent
        ||
        null
            ,
            
        mrr: data.mrr
        ||
        null
            ,
            
        arr: data.arr
        ||
        null
            ,
            
        accounts_receivable: data.accounts_receivable
        ||
        null
            ,
            
        accounts_payable: data.accounts_payable
        ||
        null
            ,
            
        runway_months: data.runway_months
        ||
        null
            ,
            
        quality_grade: data.quality_grade
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await metrics_snapshots.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await metrics_snapshots.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return metrics_snapshots;
    }
    

    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 metrics_snapshotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                as_of_at: item.as_of_at
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                cash_balance: item.cash_balance
            ||
            null
            ,
            
                net_burn_monthly: item.net_burn_monthly
            ||
            null
            ,
            
                gross_margin_percent: item.gross_margin_percent
            ||
            null
            ,
            
                mrr: item.mrr
            ||
            null
            ,
            
                arr: item.arr
            ||
            null
            ,
            
                accounts_receivable: item.accounts_receivable
            ||
            null
            ,
            
                accounts_payable: item.accounts_payable
            ||
            null
            ,
            
                runway_months: item.runway_months
            ||
            null
            ,
            
                quality_grade: item.quality_grade
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return metrics_snapshots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.as_of_at !== undefined) updatePayload.as_of_at = data.as_of_at;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.cash_balance !== undefined) updatePayload.cash_balance = data.cash_balance;
        
        
        if (data.net_burn_monthly !== undefined) updatePayload.net_burn_monthly = data.net_burn_monthly;
        
        
        if (data.gross_margin_percent !== undefined) updatePayload.gross_margin_percent = data.gross_margin_percent;
        
        
        if (data.mrr !== undefined) updatePayload.mrr = data.mrr;
        
        
        if (data.arr !== undefined) updatePayload.arr = data.arr;
        
        
        if (data.accounts_receivable !== undefined) updatePayload.accounts_receivable = data.accounts_receivable;
        
        
        if (data.accounts_payable !== undefined) updatePayload.accounts_payable = data.accounts_payable;
        
        
        if (data.runway_months !== undefined) updatePayload.runway_months = data.runway_months;
        
        
        if (data.quality_grade !== undefined) updatePayload.quality_grade = data.quality_grade;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await metrics_snapshots.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await metrics_snapshots.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return metrics_snapshots;
    }

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

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

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


        return metrics_snapshots;
    }

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

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

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

        await metrics_snapshots.destroy({
            transaction
        });

        return metrics_snapshots;
    }

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

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

        if (!metrics_snapshots) {
            return metrics_snapshots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.workspace = await metrics_snapshots.getWorkspace({
            transaction
        });
        
        
        output.organizations = await metrics_snapshots.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'metrics_snapshots',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    as_of_at: {
                    ...where.as_of_at,
                            [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.net_burn_monthlyRange) {
                const [start, end] = filter.net_burn_monthlyRange;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.metrics_snapshots.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'metrics_snapshots',
                        'currency',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

