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

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

        const ai_requests = await db.ai_requests.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        prompt_tokens: data.prompt_tokens
        ||
        null
            ,
            
        completion_tokens: data.completion_tokens
        ||
        null
            ,
            
        estimated_cost: data.estimated_cost
        ||
        null
            ,
            
        model_used: data.model_used
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
        contains_private_data: data.contains_private_data
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_requests.setUser( data.user || null, {
            transaction,
        });
        
        await ai_requests.setAi_task( data.ai_task || null, {
            transaction,
        });
        
        await ai_requests.setAi_gateway( data.ai_gateway || null, {
            transaction,
        });
        

        

        

        return ai_requests;
    }
    

    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_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                prompt_tokens: item.prompt_tokens
            ||
            null
            ,
            
                completion_tokens: item.completion_tokens
            ||
            null
            ,
            
                estimated_cost: item.estimated_cost
            ||
            null
            ,
            
                model_used: item.model_used
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
                contains_private_data: item.contains_private_data
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.prompt_tokens !== undefined) updatePayload.prompt_tokens = data.prompt_tokens;
        
        
        if (data.completion_tokens !== undefined) updatePayload.completion_tokens = data.completion_tokens;
        
        
        if (data.estimated_cost !== undefined) updatePayload.estimated_cost = data.estimated_cost;
        
        
        if (data.model_used !== undefined) updatePayload.model_used = data.model_used;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        if (data.contains_private_data !== undefined) updatePayload.contains_private_data = data.contains_private_data;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await ai_requests.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.ai_task !== undefined) {
            await ai_requests.setAi_task(
              
              data.ai_task,
              
              { transaction }
            );
        }
        
        if (data.ai_gateway !== undefined) {
            await ai_requests.setAi_gateway(
              
              data.ai_gateway,
              
              { transaction }
            );
        }
        

        
        

        

        return ai_requests;
    }

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

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

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


        return ai_requests;
    }

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

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

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

        await ai_requests.destroy({
            transaction
        });

        return ai_requests;
    }

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

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

        if (!ai_requests) {
            return ai_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ai_outputs_ai_request = await ai_requests.getAi_outputs_ai_request({
            transaction
        });
        
        
        
        output.messages_ai_request = await ai_requests.getMessages_ai_request({
            transaction
        });
        
        
        
        
        
        
        output.user = await ai_requests.getUser({
            transaction
        });
        
        
        output.ai_task = await ai_requests.getAi_task({
            transaction
        });
        
        
        output.ai_gateway = await ai_requests.getAi_gateway({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.model_used) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_requests',
                        'model_used',
                        filter.model_used,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_requests',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

            
            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.completed_atRange) {
                const [start, end] = filter.completed_atRange;

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

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

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

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.contains_private_data) {
                where = {
                    ...where,
                contains_private_data: filter.contains_private_data,
            };
            }
            


      

      

      



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

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

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

    
};

