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

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

        const generation_outputs = await db.generation_outputs.create(
            {
                id: data.id || undefined,
        
        output_type: data.output_type
        ||
        null
            ,
            
        output_title: data.output_title
        ||
        null
            ,
            
        output_content: data.output_content
        ||
        null
            ,
            
        is_exported: data.is_exported
        ||
        false
        
            ,
            
        exported_at: data.exported_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await generation_outputs.setGeneration_run( data.generation_run || null, {
            transaction,
        });
        

        

        

        return generation_outputs;
    }
    

    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 generation_outputsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                output_type: item.output_type
            ||
            null
            ,
            
                output_title: item.output_title
            ||
            null
            ,
            
                output_content: item.output_content
            ||
            null
            ,
            
                is_exported: item.is_exported
            ||
            false
        
            ,
            
                exported_at: item.exported_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return generation_outputs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.output_type !== undefined) updatePayload.output_type = data.output_type;
        
        
        if (data.output_title !== undefined) updatePayload.output_title = data.output_title;
        
        
        if (data.output_content !== undefined) updatePayload.output_content = data.output_content;
        
        
        if (data.is_exported !== undefined) updatePayload.is_exported = data.is_exported;
        
        
        if (data.exported_at !== undefined) updatePayload.exported_at = data.exported_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.generation_run !== undefined) {
            await generation_outputs.setGeneration_run(
              
              data.generation_run,
              
              { transaction }
            );
        }
        

        
        

        

        return generation_outputs;
    }

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

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

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


        return generation_outputs;
    }

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

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

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

        await generation_outputs.destroy({
            transaction
        });

        return generation_outputs;
    }

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

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

        if (!generation_outputs) {
            return generation_outputs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.output_citations_generation_output = await generation_outputs.getOutput_citations_generation_output({
            transaction
        });
        
        
        output.feedback_entries_generation_output = await generation_outputs.getFeedback_entries_generation_output({
            transaction
        });
        
        
        
        
        
        
        
        
        output.generation_run = await generation_outputs.getGeneration_run({
            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_runs,
        as: 'generation_run',
        
        where: filter.generation_run ? {
          [Op.or]: [
            { id: { [Op.in]: filter.generation_run.split('|').map(term => Utils.uuid(term)) } },
            {
              model_label: {
                [Op.or]: filter.generation_run.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.output_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'generation_outputs',
                        'output_title',
                        filter.output_title,
                    ),
                };
            }
            
            if (filter.output_content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'generation_outputs',
                        'output_content',
                        filter.output_content,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



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

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

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

    
};

