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

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

        const economic_models = await db.economic_models.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        gold_price: data.gold_price
        ||
        null
            ,
            
        discount_rate_pct: data.discount_rate_pct
        ||
        null
            ,
            
        throughput_tpd: data.throughput_tpd
        ||
        null
            ,
            
        recovery_pct: data.recovery_pct
        ||
        null
            ,
            
        mine_life_years: data.mine_life_years
        ||
        null
            ,
            
        capex_total: data.capex_total
        ||
        null
            ,
            
        opex_per_tonne: data.opex_per_tonne
        ||
        null
            ,
            
        npv: data.npv
        ||
        null
            ,
            
        irr_pct: data.irr_pct
        ||
        null
            ,
            
        payback_years: data.payback_years
        ||
        null
            ,
            
        assumptions_json: data.assumptions_json
        ||
        null
            ,
            
        sensitivity_json: data.sensitivity_json
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await economic_models.setProject( data.project || null, {
            transaction,
        });
        
        await economic_models.setPhase( data.phase || null, {
            transaction,
        });
        
        await economic_models.setFlowsheet( data.flowsheet || null, {
            transaction,
        });
        
        await economic_models.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return economic_models;
    }
    

    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 economic_modelsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                gold_price: item.gold_price
            ||
            null
            ,
            
                discount_rate_pct: item.discount_rate_pct
            ||
            null
            ,
            
                throughput_tpd: item.throughput_tpd
            ||
            null
            ,
            
                recovery_pct: item.recovery_pct
            ||
            null
            ,
            
                mine_life_years: item.mine_life_years
            ||
            null
            ,
            
                capex_total: item.capex_total
            ||
            null
            ,
            
                opex_per_tonne: item.opex_per_tonne
            ||
            null
            ,
            
                npv: item.npv
            ||
            null
            ,
            
                irr_pct: item.irr_pct
            ||
            null
            ,
            
                payback_years: item.payback_years
            ||
            null
            ,
            
                assumptions_json: item.assumptions_json
            ||
            null
            ,
            
                sensitivity_json: item.sensitivity_json
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return economic_models;
    }

    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 economic_models = await db.economic_models.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.gold_price !== undefined) updatePayload.gold_price = data.gold_price;
        
        
        if (data.discount_rate_pct !== undefined) updatePayload.discount_rate_pct = data.discount_rate_pct;
        
        
        if (data.throughput_tpd !== undefined) updatePayload.throughput_tpd = data.throughput_tpd;
        
        
        if (data.recovery_pct !== undefined) updatePayload.recovery_pct = data.recovery_pct;
        
        
        if (data.mine_life_years !== undefined) updatePayload.mine_life_years = data.mine_life_years;
        
        
        if (data.capex_total !== undefined) updatePayload.capex_total = data.capex_total;
        
        
        if (data.opex_per_tonne !== undefined) updatePayload.opex_per_tonne = data.opex_per_tonne;
        
        
        if (data.npv !== undefined) updatePayload.npv = data.npv;
        
        
        if (data.irr_pct !== undefined) updatePayload.irr_pct = data.irr_pct;
        
        
        if (data.payback_years !== undefined) updatePayload.payback_years = data.payback_years;
        
        
        if (data.assumptions_json !== undefined) updatePayload.assumptions_json = data.assumptions_json;
        
        
        if (data.sensitivity_json !== undefined) updatePayload.sensitivity_json = data.sensitivity_json;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await economic_models.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.phase !== undefined) {
            await economic_models.setPhase(
              
              data.phase,
              
              { transaction }
            );
        }
        
        if (data.flowsheet !== undefined) {
            await economic_models.setFlowsheet(
              
              data.flowsheet,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await economic_models.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return economic_models;
    }

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

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

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


        return economic_models;
    }

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

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

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

        await economic_models.destroy({
            transaction
        });

        return economic_models;
    }

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

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

        if (!economic_models) {
            return economic_models;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.capex_items_economic_model = await economic_models.getCapex_items_economic_model({
            transaction
        });
        
        
        output.opex_items_economic_model = await economic_models.getOpex_items_economic_model({
            transaction
        });
        
        
        output.monte_carlo_runs_economic_model = await economic_models.getMonte_carlo_runs_economic_model({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.project = await economic_models.getProject({
            transaction
        });
        
        
        output.phase = await economic_models.getPhase({
            transaction
        });
        
        
        output.flowsheet = await economic_models.getFlowsheet({
            transaction
        });
        
        
        output.organizations = await economic_models.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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.flowsheets,
        as: 'flowsheet',
        
        where: filter.flowsheet ? {
          [Op.or]: [
            { id: { [Op.in]: filter.flowsheet.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.flowsheet.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'economic_models',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.assumptions_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'economic_models',
                        'assumptions_json',
                        filter.assumptions_json,
                    ),
                };
            }
            
            if (filter.sensitivity_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'economic_models',
                        'sensitivity_json',
                        filter.sensitivity_json,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

      

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

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

    
};

