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

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

        const llm_models = await db.llm_models.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        model_code: data.model_code
        ||
        null
            ,
            
        max_input_tokens: data.max_input_tokens
        ||
        null
            ,
            
        max_output_tokens: data.max_output_tokens
        ||
        null
            ,
            
        supports_vision: data.supports_vision
        ||
        false
        
            ,
            
        supports_function_calling: data.supports_function_calling
        ||
        false
        
            ,
            
        price_per_million_input_tokens: data.price_per_million_input_tokens
        ||
        null
            ,
            
        price_per_million_output_tokens: data.price_per_million_output_tokens
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await llm_models.setProvider( data.provider || null, {
            transaction,
        });
        
        await llm_models.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return llm_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 llm_modelsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                model_code: item.model_code
            ||
            null
            ,
            
                max_input_tokens: item.max_input_tokens
            ||
            null
            ,
            
                max_output_tokens: item.max_output_tokens
            ||
            null
            ,
            
                supports_vision: item.supports_vision
            ||
            false
        
            ,
            
                supports_function_calling: item.supports_function_calling
            ||
            false
        
            ,
            
                price_per_million_input_tokens: item.price_per_million_input_tokens
            ||
            null
            ,
            
                price_per_million_output_tokens: item.price_per_million_output_tokens
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.model_code !== undefined) updatePayload.model_code = data.model_code;
        
        
        if (data.max_input_tokens !== undefined) updatePayload.max_input_tokens = data.max_input_tokens;
        
        
        if (data.max_output_tokens !== undefined) updatePayload.max_output_tokens = data.max_output_tokens;
        
        
        if (data.supports_vision !== undefined) updatePayload.supports_vision = data.supports_vision;
        
        
        if (data.supports_function_calling !== undefined) updatePayload.supports_function_calling = data.supports_function_calling;
        
        
        if (data.price_per_million_input_tokens !== undefined) updatePayload.price_per_million_input_tokens = data.price_per_million_input_tokens;
        
        
        if (data.price_per_million_output_tokens !== undefined) updatePayload.price_per_million_output_tokens = data.price_per_million_output_tokens;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return llm_models;
    }

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

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

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


        return llm_models;
    }

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

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

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

        await llm_models.destroy({
            transaction
        });

        return llm_models;
    }

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

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

        if (!llm_models) {
            return llm_models;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.chats_model = await llm_models.getChats_model({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.provider = await llm_models.getProvider({
            transaction
        });
        
        
        output.organizations = await llm_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.llm_providers,
        as: 'provider',
        
        where: filter.provider ? {
          [Op.or]: [
            { id: { [Op.in]: filter.provider.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.provider.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'llm_models',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.model_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'llm_models',
                        'model_code',
                        filter.model_code,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.supports_vision) {
                where = {
                    ...where,
                supports_vision: filter.supports_vision,
            };
            }
            
            if (filter.supports_function_calling) {
                where = {
                    ...where,
                supports_function_calling: filter.supports_function_calling,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      
      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.llm_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(
                        'llm_models',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

