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

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

        const opex_items = await db.opex_items.create(
            {
                id: data.id || undefined,
        
        opex_type: data.opex_type
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        rate: data.rate
        ||
        null
            ,
            
        rate_unit: data.rate_unit
        ||
        null
            ,
            
        unit_cost: data.unit_cost
        ||
        null
            ,
            
        cost_unit: data.cost_unit
        ||
        null
            ,
            
        annual_cost: data.annual_cost
        ||
        null
            ,
            
        basis_notes: data.basis_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await opex_items.setEconomic_model( data.economic_model || null, {
            transaction,
        });
        
        await opex_items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await opex_items.setSource_tests(data.source_tests || [], {
            transaction,
        });
        

        

        return opex_items;
    }
    

    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 opex_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                opex_type: item.opex_type
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                rate: item.rate
            ||
            null
            ,
            
                rate_unit: item.rate_unit
            ||
            null
            ,
            
                unit_cost: item.unit_cost
            ||
            null
            ,
            
                cost_unit: item.cost_unit
            ||
            null
            ,
            
                annual_cost: item.annual_cost
            ||
            null
            ,
            
                basis_notes: item.basis_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return opex_items;
    }

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


        

        const updatePayload = {};
        
        if (data.opex_type !== undefined) updatePayload.opex_type = data.opex_type;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.rate !== undefined) updatePayload.rate = data.rate;
        
        
        if (data.rate_unit !== undefined) updatePayload.rate_unit = data.rate_unit;
        
        
        if (data.unit_cost !== undefined) updatePayload.unit_cost = data.unit_cost;
        
        
        if (data.cost_unit !== undefined) updatePayload.cost_unit = data.cost_unit;
        
        
        if (data.annual_cost !== undefined) updatePayload.annual_cost = data.annual_cost;
        
        
        if (data.basis_notes !== undefined) updatePayload.basis_notes = data.basis_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.economic_model !== undefined) {
            await opex_items.setEconomic_model(
              
              data.economic_model,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await opex_items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.source_tests !== undefined) {
            await opex_items.setSource_tests(data.source_tests, { transaction });
        }
        

        

        return opex_items;
    }

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

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

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


        return opex_items;
    }

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

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

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

        await opex_items.destroy({
            transaction
        });

        return opex_items;
    }

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

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

        if (!opex_items) {
            return opex_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.economic_model = await opex_items.getEconomic_model({
            transaction
        });
        
        
        output.source_tests = await opex_items.getSource_tests({
            transaction
        });
        
        
        output.organizations = await opex_items.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.economic_models,
        as: 'economic_model',
        
        where: filter.economic_model ? {
          [Op.or]: [
            { id: { [Op.in]: filter.economic_model.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.economic_model.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.metallurgical_tests,
        as: 'source_tests',
        required: false,
      },


    ];

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

            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'opex_items',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.rate_unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'opex_items',
                        'rate_unit',
                        filter.rate_unit,
                    ),
                };
            }
            
            if (filter.cost_unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'opex_items',
                        'cost_unit',
                        filter.cost_unit,
                    ),
                };
            }
            
            if (filter.basis_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'opex_items',
                        'basis_notes',
                        filter.basis_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

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

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


      if (filter.source_tests) {
        const searchTerms = filter.source_tests.split('|');

        include = [
          {
            model: db.metallurgical_tests,
            as: 'source_tests_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  lab_reference: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

