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

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

        const generation_runs = await db.generation_runs.create(
            {
                id: data.id || undefined,
        
        run_type: data.run_type
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        run_status: data.run_status
        ||
        null
            ,
            
        input_prompt: data.input_prompt
        ||
        null
            ,
            
        model_label: data.model_label
        ||
        null
            ,
            
        temperature: data.temperature
        ||
        null
            ,
            
        retrieved_chunk_count: data.retrieved_chunk_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await generation_runs.setAd_project( data.ad_project || null, {
            transaction,
        });
        
        await generation_runs.setRequested_by( data.requested_by || null, {
            transaction,
        });
        

        

        

        return generation_runs;
    }
    

    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_runsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                run_type: item.run_type
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                run_status: item.run_status
            ||
            null
            ,
            
                input_prompt: item.input_prompt
            ||
            null
            ,
            
                model_label: item.model_label
            ||
            null
            ,
            
                temperature: item.temperature
            ||
            null
            ,
            
                retrieved_chunk_count: item.retrieved_chunk_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return generation_runs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.run_type !== undefined) updatePayload.run_type = data.run_type;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.run_status !== undefined) updatePayload.run_status = data.run_status;
        
        
        if (data.input_prompt !== undefined) updatePayload.input_prompt = data.input_prompt;
        
        
        if (data.model_label !== undefined) updatePayload.model_label = data.model_label;
        
        
        if (data.temperature !== undefined) updatePayload.temperature = data.temperature;
        
        
        if (data.retrieved_chunk_count !== undefined) updatePayload.retrieved_chunk_count = data.retrieved_chunk_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.ad_project !== undefined) {
            await generation_runs.setAd_project(
              
              data.ad_project,
              
              { transaction }
            );
        }
        
        if (data.requested_by !== undefined) {
            await generation_runs.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        

        
        

        

        return generation_runs;
    }

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

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

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


        return generation_runs;
    }

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

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

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

        await generation_runs.destroy({
            transaction
        });

        return generation_runs;
    }

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

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

        if (!generation_runs) {
            return generation_runs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.generation_outputs_generation_run = await generation_runs.getGeneration_outputs_generation_run({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.ad_project = await generation_runs.getAd_project({
            transaction
        });
        
        
        output.requested_by = await generation_runs.getRequested_by({
            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.ad_projects,
        as: 'ad_project',
        
        where: filter.ad_project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.ad_project.split('|').map(term => Utils.uuid(term)) } },
            {
              project_name: {
                [Op.or]: filter.ad_project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.input_prompt) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'generation_runs',
                        'input_prompt',
                        filter.input_prompt,
                    ),
                };
            }
            
            if (filter.model_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'generation_runs',
                        'model_label',
                        filter.model_label,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.run_type) {
                where = {
                    ...where,
                run_type: filter.run_type,
            };
            }
            
            if (filter.run_status) {
                where = {
                    ...where,
                run_status: filter.run_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.generation_runs.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_runs',
                        'model_label',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

