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

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

        const output_citations = await db.output_citations.create(
            {
                id: data.id || undefined,
        
        relevance_score: data.relevance_score
        ||
        null
            ,
            
        citation_note: data.citation_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await output_citations.setGeneration_output( data.generation_output || null, {
            transaction,
        });
        
        await output_citations.setKnowledge_chunk( data.knowledge_chunk || null, {
            transaction,
        });
        

        

        

        return output_citations;
    }
    

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

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

        // For each item created, replace relation files
        

        return output_citations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.relevance_score !== undefined) updatePayload.relevance_score = data.relevance_score;
        
        
        if (data.citation_note !== undefined) updatePayload.citation_note = data.citation_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.generation_output !== undefined) {
            await output_citations.setGeneration_output(
              
              data.generation_output,
              
              { transaction }
            );
        }
        
        if (data.knowledge_chunk !== undefined) {
            await output_citations.setKnowledge_chunk(
              
              data.knowledge_chunk,
              
              { transaction }
            );
        }
        

        
        

        

        return output_citations;
    }

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

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

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


        return output_citations;
    }

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

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

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

        await output_citations.destroy({
            transaction
        });

        return output_citations;
    }

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

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

        if (!output_citations) {
            return output_citations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.generation_output = await output_citations.getGeneration_output({
            transaction
        });
        
        
        output.knowledge_chunk = await output_citations.getKnowledge_chunk({
            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.generation_outputs,
        as: 'generation_output',
        
        where: filter.generation_output ? {
          [Op.or]: [
            { id: { [Op.in]: filter.generation_output.split('|').map(term => Utils.uuid(term)) } },
            {
              output_title: {
                [Op.or]: filter.generation_output.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.knowledge_chunks,
        as: 'knowledge_chunk',
        
        where: filter.knowledge_chunk ? {
          [Op.or]: [
            { id: { [Op.in]: filter.knowledge_chunk.split('|').map(term => Utils.uuid(term)) } },
            {
              chunk_label: {
                [Op.or]: filter.knowledge_chunk.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.citation_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'output_citations',
                        'citation_note',
                        filter.citation_note,
                    ),
                };
            }
            

            
            

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

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

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

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

            


      

      



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

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

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

    
};

