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

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

        const equipment_items = await db.equipment_items.create(
            {
                id: data.id || undefined,
        
        equipment_type: data.equipment_type
        ||
        null
            ,
            
        manufacturer: data.manufacturer
        ||
        null
            ,
            
        model: data.model
        ||
        null
            ,
            
        capacity: data.capacity
        ||
        null
            ,
            
        capacity_unit: data.capacity_unit
        ||
        null
            ,
            
        power_kw: data.power_kw
        ||
        null
            ,
            
        base_capex_usd: data.base_capex_usd
        ||
        null
            ,
            
        install_factor: data.install_factor
        ||
        null
            ,
            
        opex_per_unit: data.opex_per_unit
        ||
        null
            ,
            
        opex_unit: data.opex_unit
        ||
        null
            ,
            
        vendor_quote_reference: data.vendor_quote_reference
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await equipment_items.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.equipment_items.getTableName(),
                belongsToColumn: 'datasheet_files',
                belongsToId: equipment_items.id,
            },
            data.datasheet_files,
            options,
        );
        

        return equipment_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 equipment_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                equipment_type: item.equipment_type
            ||
            null
            ,
            
                manufacturer: item.manufacturer
            ||
            null
            ,
            
                model: item.model
            ||
            null
            ,
            
                capacity: item.capacity
            ||
            null
            ,
            
                capacity_unit: item.capacity_unit
            ||
            null
            ,
            
                power_kw: item.power_kw
            ||
            null
            ,
            
                base_capex_usd: item.base_capex_usd
            ||
            null
            ,
            
                install_factor: item.install_factor
            ||
            null
            ,
            
                opex_per_unit: item.opex_per_unit
            ||
            null
            ,
            
                opex_unit: item.opex_unit
            ||
            null
            ,
            
                vendor_quote_reference: item.vendor_quote_reference
            ||
            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 equipment_items = await db.equipment_items.bulkCreate(equipment_itemsData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < equipment_items.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.equipment_items.getTableName(),
                    belongsToColumn: 'datasheet_files',
                    belongsToId: equipment_items[i].id,
                },
                data[i].datasheet_files,
                options,
            );
        }
        

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


        

        const updatePayload = {};
        
        if (data.equipment_type !== undefined) updatePayload.equipment_type = data.equipment_type;
        
        
        if (data.manufacturer !== undefined) updatePayload.manufacturer = data.manufacturer;
        
        
        if (data.model !== undefined) updatePayload.model = data.model;
        
        
        if (data.capacity !== undefined) updatePayload.capacity = data.capacity;
        
        
        if (data.capacity_unit !== undefined) updatePayload.capacity_unit = data.capacity_unit;
        
        
        if (data.power_kw !== undefined) updatePayload.power_kw = data.power_kw;
        
        
        if (data.base_capex_usd !== undefined) updatePayload.base_capex_usd = data.base_capex_usd;
        
        
        if (data.install_factor !== undefined) updatePayload.install_factor = data.install_factor;
        
        
        if (data.opex_per_unit !== undefined) updatePayload.opex_per_unit = data.opex_per_unit;
        
        
        if (data.opex_unit !== undefined) updatePayload.opex_unit = data.opex_unit;
        
        
        if (data.vendor_quote_reference !== undefined) updatePayload.vendor_quote_reference = data.vendor_quote_reference;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await equipment_items.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.equipment_items.getTableName(),
                belongsToColumn: 'datasheet_files',
                belongsToId: equipment_items.id,
            },
            data.datasheet_files,
            options,
        );
        

        return equipment_items;
    }

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

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

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


        return equipment_items;
    }

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

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

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

        await equipment_items.destroy({
            transaction
        });

        return equipment_items;
    }

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

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

        if (!equipment_items) {
            return equipment_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.flowsheet_nodes_equipment_item = await equipment_items.getFlowsheet_nodes_equipment_item({
            transaction
        });
        
        
        
        
        
        output.capex_items_equipment_item = await equipment_items.getCapex_items_equipment_item({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await equipment_items.getOrganization({
            transaction
        });
        
        
        output.datasheet_files = await equipment_items.getDatasheet_files({
            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.organizations,
        as: 'organization',
        
      },



      {
        model: db.file,
        as: 'datasheet_files',
      },

    ];

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

            
            if (filter.manufacturer) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'equipment_items',
                        'manufacturer',
                        filter.manufacturer,
                    ),
                };
            }
            
            if (filter.model) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'equipment_items',
                        'model',
                        filter.model,
                    ),
                };
            }
            
            if (filter.capacity_unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'equipment_items',
                        'capacity_unit',
                        filter.capacity_unit,
                    ),
                };
            }
            
            if (filter.opex_unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'equipment_items',
                        'opex_unit',
                        filter.opex_unit,
                    ),
                };
            }
            
            if (filter.vendor_quote_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'equipment_items',
                        'vendor_quote_reference',
                        filter.vendor_quote_reference,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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


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

        where = {
          ...where,
          organizationId: {[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.equipment_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(
                        'equipment_items',
                        'model',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

