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

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

        const knowledge_documents = await db.knowledge_documents.create(
            {
                id: data.id || undefined,
        
        document_title: data.document_title
        ||
        null
            ,
            
        ingestion_status: data.ingestion_status
        ||
        null
            ,
            
        language: data.language
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        ingested_at: data.ingested_at
        ||
        null
            ,
            
        document_summary: data.document_summary
        ||
        null
            ,
            
        tags_csv: data.tags_csv
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await knowledge_documents.setKnowledge_source( data.knowledge_source || null, {
            transaction,
        });
        

        

        

        return knowledge_documents;
    }
    

    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_documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                document_title: item.document_title
            ||
            null
            ,
            
                ingestion_status: item.ingestion_status
            ||
            null
            ,
            
                language: item.language
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
                ingested_at: item.ingested_at
            ||
            null
            ,
            
                document_summary: item.document_summary
            ||
            null
            ,
            
                tags_csv: item.tags_csv
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return knowledge_documents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.document_title !== undefined) updatePayload.document_title = data.document_title;
        
        
        if (data.ingestion_status !== undefined) updatePayload.ingestion_status = data.ingestion_status;
        
        
        if (data.language !== undefined) updatePayload.language = data.language;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.ingested_at !== undefined) updatePayload.ingested_at = data.ingested_at;
        
        
        if (data.document_summary !== undefined) updatePayload.document_summary = data.document_summary;
        
        
        if (data.tags_csv !== undefined) updatePayload.tags_csv = data.tags_csv;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.knowledge_source !== undefined) {
            await knowledge_documents.setKnowledge_source(
              
              data.knowledge_source,
              
              { transaction }
            );
        }
        

        
        

        

        return knowledge_documents;
    }

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

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

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


        return knowledge_documents;
    }

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

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

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

        await knowledge_documents.destroy({
            transaction
        });

        return knowledge_documents;
    }

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

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

        if (!knowledge_documents) {
            return knowledge_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.knowledge_chunks_knowledge_document = await knowledge_documents.getKnowledge_chunks_knowledge_document({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.knowledge_source = await knowledge_documents.getKnowledge_source({
            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_sources,
        as: 'knowledge_source',
        
        where: filter.knowledge_source ? {
          [Op.or]: [
            { id: { [Op.in]: filter.knowledge_source.split('|').map(term => Utils.uuid(term)) } },
            {
              source_name: {
                [Op.or]: filter.knowledge_source.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.document_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_documents',
                        'document_title',
                        filter.document_title,
                    ),
                };
            }
            
            if (filter.language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_documents',
                        'language',
                        filter.language,
                    ),
                };
            }
            
            if (filter.document_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_documents',
                        'document_summary',
                        filter.document_summary,
                    ),
                };
            }
            
            if (filter.tags_csv) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_documents',
                        'tags_csv',
                        filter.tags_csv,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



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

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

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

    
};

