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

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

        const knowledge_nodes = await db.knowledge_nodes.create(
            {
                id: data.id || undefined,
        
        node_name: data.node_name
        ||
        null
            ,
            
        node_type: data.node_type
        ||
        null
            ,
            
        node_description: data.node_description
        ||
        null
            ,
            
        importance_score: data.importance_score
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        
        await knowledge_nodes.setSupporting_chunks(data.supporting_chunks || [], {
            transaction,
        });
        

        

        return knowledge_nodes;
    }
    

    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 knowledge_nodesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                node_name: item.node_name
            ||
            null
            ,
            
                node_type: item.node_type
            ||
            null
            ,
            
                node_description: item.node_description
            ||
            null
            ,
            
                importance_score: item.importance_score
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return knowledge_nodes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.node_name !== undefined) updatePayload.node_name = data.node_name;
        
        
        if (data.node_type !== undefined) updatePayload.node_type = data.node_type;
        
        
        if (data.node_description !== undefined) updatePayload.node_description = data.node_description;
        
        
        if (data.importance_score !== undefined) updatePayload.importance_score = data.importance_score;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        
        if (data.supporting_chunks !== undefined) {
            await knowledge_nodes.setSupporting_chunks(data.supporting_chunks, { transaction });
        }
        

        

        return knowledge_nodes;
    }

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

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

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


        return knowledge_nodes;
    }

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

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

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

        await knowledge_nodes.destroy({
            transaction
        });

        return knowledge_nodes;
    }

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

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

        if (!knowledge_nodes) {
            return knowledge_nodes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.supporting_chunks = await knowledge_nodes.getSupporting_chunks({
            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.knowledge_chunks,
        as: 'supporting_chunks',
        required: false,
      },


    ];

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

            
            if (filter.node_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_nodes',
                        'node_name',
                        filter.node_name,
                    ),
                };
            }
            
            if (filter.node_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_nodes',
                        'node_description',
                        filter.node_description,
                    ),
                };
            }
            

            
            

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

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

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

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

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



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

        include = [
          {
            model: db.knowledge_chunks,
            as: 'supporting_chunks_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  chunk_label: {
                    [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,
                        },
                    };
                }
            }
        }
        

        

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

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

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

    
};

