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

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

        const knowledge_sources = await db.knowledge_sources.create(
            {
                id: data.id || undefined,
        
        source_type: data.source_type
        ||
        null
            ,
            
        source_name: data.source_name
        ||
        null
            ,
            
        source_url: data.source_url
        ||
        null
            ,
            
        trust_tier: data.trust_tier
        ||
        null
            ,
            
        content_domain: data.content_domain
        ||
        null
            ,
            
        last_ingested_at: data.last_ingested_at
        ||
        null
            ,
            
        next_refresh_at: data.next_refresh_at
        ||
        null
            ,
            
        auto_refresh_enabled: data.auto_refresh_enabled
        ||
        false
        
            ,
            
        refresh_notes: data.refresh_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return knowledge_sources;
    }
    

    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_sourcesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                source_type: item.source_type
            ||
            null
            ,
            
                source_name: item.source_name
            ||
            null
            ,
            
                source_url: item.source_url
            ||
            null
            ,
            
                trust_tier: item.trust_tier
            ||
            null
            ,
            
                content_domain: item.content_domain
            ||
            null
            ,
            
                last_ingested_at: item.last_ingested_at
            ||
            null
            ,
            
                next_refresh_at: item.next_refresh_at
            ||
            null
            ,
            
                auto_refresh_enabled: item.auto_refresh_enabled
            ||
            false
        
            ,
            
                refresh_notes: item.refresh_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return knowledge_sources;
    }

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

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


        

        const updatePayload = {};
        
        if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
        
        
        if (data.source_name !== undefined) updatePayload.source_name = data.source_name;
        
        
        if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
        
        
        if (data.trust_tier !== undefined) updatePayload.trust_tier = data.trust_tier;
        
        
        if (data.content_domain !== undefined) updatePayload.content_domain = data.content_domain;
        
        
        if (data.last_ingested_at !== undefined) updatePayload.last_ingested_at = data.last_ingested_at;
        
        
        if (data.next_refresh_at !== undefined) updatePayload.next_refresh_at = data.next_refresh_at;
        
        
        if (data.auto_refresh_enabled !== undefined) updatePayload.auto_refresh_enabled = data.auto_refresh_enabled;
        
        
        if (data.refresh_notes !== undefined) updatePayload.refresh_notes = data.refresh_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return knowledge_sources;
    }

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

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

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


        return knowledge_sources;
    }

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

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

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

        await knowledge_sources.destroy({
            transaction
        });

        return knowledge_sources;
    }

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

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

        if (!knowledge_sources) {
            return knowledge_sources;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.knowledge_documents_knowledge_source = await knowledge_sources.getKnowledge_documents_knowledge_source({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.refresh_jobs_knowledge_source = await knowledge_sources.getRefresh_jobs_knowledge_source({
            transaction
        });
        
        
        
        
        output.uploaded_files = await knowledge_sources.getUploaded_files({
            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.file,
        as: 'uploaded_files',
      },

    ];

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

            
            if (filter.source_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_sources',
                        'source_name',
                        filter.source_name,
                    ),
                };
            }
            
            if (filter.source_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_sources',
                        'source_url',
                        filter.source_url,
                    ),
                };
            }
            
            if (filter.refresh_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_sources',
                        'refresh_notes',
                        filter.refresh_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.source_type) {
                where = {
                    ...where,
                source_type: filter.source_type,
            };
            }
            
            if (filter.trust_tier) {
                where = {
                    ...where,
                trust_tier: filter.trust_tier,
            };
            }
            
            if (filter.content_domain) {
                where = {
                    ...where,
                content_domain: filter.content_domain,
            };
            }
            
            if (filter.auto_refresh_enabled) {
                where = {
                    ...where,
                auto_refresh_enabled: filter.auto_refresh_enabled,
            };
            }
            




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

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

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

    
};

