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

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

        const ai_models = await db.ai_models.create(
            {
                id: data.id || undefined,
        
        display_name: data.display_name
        ||
        null
            ,
            
        provider: data.provider
        ||
        null
            ,
            
        model_key: data.model_key
        ||
        null
            ,
            
        capability_class: data.capability_class
        ||
        null
            ,
            
        max_context_tokens: data.max_context_tokens
        ||
        null
            ,
            
        input_cost_per_1k: data.input_cost_per_1k
        ||
        null
            ,
            
        output_cost_per_1k: data.output_cost_per_1k
        ||
        null
            ,
            
        supports_streaming: data.supports_streaming
        ||
        false
        
            ,
            
        supports_function_calls: data.supports_function_calls
        ||
        false
        
            ,
            
        supports_vision: data.supports_vision
        ||
        false
        
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_models.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return ai_models;
    }
    

    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_modelsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                display_name: item.display_name
            ||
            null
            ,
            
                provider: item.provider
            ||
            null
            ,
            
                model_key: item.model_key
            ||
            null
            ,
            
                capability_class: item.capability_class
            ||
            null
            ,
            
                max_context_tokens: item.max_context_tokens
            ||
            null
            ,
            
                input_cost_per_1k: item.input_cost_per_1k
            ||
            null
            ,
            
                output_cost_per_1k: item.output_cost_per_1k
            ||
            null
            ,
            
                supports_streaming: item.supports_streaming
            ||
            false
        
            ,
            
                supports_function_calls: item.supports_function_calls
            ||
            false
        
            ,
            
                supports_vision: item.supports_vision
            ||
            false
        
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_models;
    }

    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_models = await db.ai_models.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.model_key !== undefined) updatePayload.model_key = data.model_key;
        
        
        if (data.capability_class !== undefined) updatePayload.capability_class = data.capability_class;
        
        
        if (data.max_context_tokens !== undefined) updatePayload.max_context_tokens = data.max_context_tokens;
        
        
        if (data.input_cost_per_1k !== undefined) updatePayload.input_cost_per_1k = data.input_cost_per_1k;
        
        
        if (data.output_cost_per_1k !== undefined) updatePayload.output_cost_per_1k = data.output_cost_per_1k;
        
        
        if (data.supports_streaming !== undefined) updatePayload.supports_streaming = data.supports_streaming;
        
        
        if (data.supports_function_calls !== undefined) updatePayload.supports_function_calls = data.supports_function_calls;
        
        
        if (data.supports_vision !== undefined) updatePayload.supports_vision = data.supports_vision;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return ai_models;
    }

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

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

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


        return ai_models;
    }

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

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

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

        await ai_models.destroy({
            transaction
        });

        return ai_models;
    }

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

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

        if (!ai_models) {
            return ai_models;
        }

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

        
        
        
        
        
        
        
        
        output.ai_agents_default_model = await ai_models.getAi_agents_default_model({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.usage_events_model = await ai_models.getUsage_events_model({
            transaction
        });
        
        
        
        
        output.organizations = await ai_models.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.display_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_models',
                        'display_name',
                        filter.display_name,
                    ),
                };
            }
            
            if (filter.provider) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_models',
                        'provider',
                        filter.provider,
                    ),
                };
            }
            
            if (filter.model_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_models',
                        'model_key',
                        filter.model_key,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.capability_class) {
                where = {
                    ...where,
                capability_class: filter.capability_class,
            };
            }
            
            if (filter.supports_streaming) {
                where = {
                    ...where,
                supports_streaming: filter.supports_streaming,
            };
            }
            
            if (filter.supports_function_calls) {
                where = {
                    ...where,
                supports_function_calls: filter.supports_function_calls,
            };
            }
            
            if (filter.supports_vision) {
                where = {
                    ...where,
                supports_vision: filter.supports_vision,
            };
            }
            
            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_models.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_models',
                        'display_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

