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

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

        const ai_runs = await db.ai_runs.create(
            {
                id: data.id || undefined,
        
        run_type: data.run_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        prompt: data.prompt
        ||
        null
            ,
            
        result_text: data.result_text
        ||
        null
            ,
            
        cost_usd: data.cost_usd
        ||
        null
            ,
            
        tokens_in: data.tokens_in
        ||
        null
            ,
            
        tokens_out: data.tokens_out
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_runs.setProject( data.project || null, {
            transaction,
        });
        
        await ai_runs.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return ai_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 ai_runsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                run_type: item.run_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                prompt: item.prompt
            ||
            null
            ,
            
                result_text: item.result_text
            ||
            null
            ,
            
                cost_usd: item.cost_usd
            ||
            null
            ,
            
                tokens_in: item.tokens_in
            ||
            null
            ,
            
                tokens_out: item.tokens_out
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return ai_runs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.run_type !== undefined) updatePayload.run_type = data.run_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.prompt !== undefined) updatePayload.prompt = data.prompt;
        
        
        if (data.result_text !== undefined) updatePayload.result_text = data.result_text;
        
        
        if (data.cost_usd !== undefined) updatePayload.cost_usd = data.cost_usd;
        
        
        if (data.tokens_in !== undefined) updatePayload.tokens_in = data.tokens_in;
        
        
        if (data.tokens_out !== undefined) updatePayload.tokens_out = data.tokens_out;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await ai_runs.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await ai_runs.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return ai_runs;
    }

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

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

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


        return ai_runs;
    }

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

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

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

        await ai_runs.destroy({
            transaction
        });

        return ai_runs;
    }

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

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

        if (!ai_runs) {
            return ai_runs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.business_plan_versions_generated_by_run = await ai_runs.getBusiness_plan_versions_generated_by_run({
            transaction
        });
        
        
        output.pitch_decks_generated_by_run = await ai_runs.getPitch_decks_generated_by_run({
            transaction
        });
        
        
        
        
        
        
        output.project = await ai_runs.getProject({
            transaction
        });
        
        
        output.result_files = await ai_runs.getResult_files({
            transaction
        });
        
        
        output.organizations = await ai_runs.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'result_files',
      },

    ];

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

            
            if (filter.prompt) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_runs',
                        'prompt',
                        filter.prompt,
                    ),
                };
            }
            
            if (filter.result_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_runs',
                        'result_text',
                        filter.result_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    finished_at: {
                    ...where.finished_at,
                            [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.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.ai_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'ai_runs',
                        'run_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

