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

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

        const knowledge_chunks = await db.knowledge_chunks.create(
            {
                id: data.id || undefined,
        
        chunk_label: data.chunk_label
        ||
        null
            ,
            
        chunk_text: data.chunk_text
        ||
        null
            ,
            
        source_locator: data.source_locator
        ||
        null
            ,
            
        recency_weight: data.recency_weight
        ||
        null
            ,
            
        quality_score: data.quality_score
        ||
        null
            ,
            
        is_sensitive: data.is_sensitive
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await knowledge_chunks.setKnowledge_document( data.knowledge_document || null, {
            transaction,
        });
        

        

        

        return knowledge_chunks;
    }
    

    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_chunksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                chunk_label: item.chunk_label
            ||
            null
            ,
            
                chunk_text: item.chunk_text
            ||
            null
            ,
            
                source_locator: item.source_locator
            ||
            null
            ,
            
                recency_weight: item.recency_weight
            ||
            null
            ,
            
                quality_score: item.quality_score
            ||
            null
            ,
            
                is_sensitive: item.is_sensitive
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return knowledge_chunks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.chunk_label !== undefined) updatePayload.chunk_label = data.chunk_label;
        
        
        if (data.chunk_text !== undefined) updatePayload.chunk_text = data.chunk_text;
        
        
        if (data.source_locator !== undefined) updatePayload.source_locator = data.source_locator;
        
        
        if (data.recency_weight !== undefined) updatePayload.recency_weight = data.recency_weight;
        
        
        if (data.quality_score !== undefined) updatePayload.quality_score = data.quality_score;
        
        
        if (data.is_sensitive !== undefined) updatePayload.is_sensitive = data.is_sensitive;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.knowledge_document !== undefined) {
            await knowledge_chunks.setKnowledge_document(
              
              data.knowledge_document,
              
              { transaction }
            );
        }
        

        
        

        

        return knowledge_chunks;
    }

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

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

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


        return knowledge_chunks;
    }

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

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

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

        await knowledge_chunks.destroy({
            transaction
        });

        return knowledge_chunks;
    }

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

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

        if (!knowledge_chunks) {
            return knowledge_chunks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.output_citations_knowledge_chunk = await knowledge_chunks.getOutput_citations_knowledge_chunk({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.knowledge_document = await knowledge_chunks.getKnowledge_document({
            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_documents,
        as: 'knowledge_document',
        
        where: filter.knowledge_document ? {
          [Op.or]: [
            { id: { [Op.in]: filter.knowledge_document.split('|').map(term => Utils.uuid(term)) } },
            {
              document_title: {
                [Op.or]: filter.knowledge_document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.chunk_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_chunks',
                        'chunk_label',
                        filter.chunk_label,
                    ),
                };
            }
            
            if (filter.chunk_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_chunks',
                        'chunk_text',
                        filter.chunk_text,
                    ),
                };
            }
            
            if (filter.source_locator) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_chunks',
                        'source_locator',
                        filter.source_locator,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



            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_chunks.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_chunks',
                        'chunk_label',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

