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

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

        const llm_providers = await db.llm_providers.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        base_url: data.base_url
        ||
        null
            ,
            
        provider_type: data.provider_type
        ||
        null
            ,
            
        region_policy: data.region_policy
        ||
        null
            ,
            
        supports_streaming: data.supports_streaming
        ||
        false
        
            ,
            
        supports_tools: data.supports_tools
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        
        await llm_providers.setApi_keys(data.api_keys || [], {
            transaction,
        });
        
        await llm_providers.setModels(data.models || [], {
            transaction,
        });
        

        

        return llm_providers;
    }
    

    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_providersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                base_url: item.base_url
            ||
            null
            ,
            
                provider_type: item.provider_type
            ||
            null
            ,
            
                region_policy: item.region_policy
            ||
            null
            ,
            
                supports_streaming: item.supports_streaming
            ||
            false
        
            ,
            
                supports_tools: item.supports_tools
            ||
            false
        
            ,
            
                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_providers = await db.llm_providers.bulkCreate(llm_providersData, { transaction });

        // For each item created, replace relation files
        

        return llm_providers;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.base_url !== undefined) updatePayload.base_url = data.base_url;
        
        
        if (data.provider_type !== undefined) updatePayload.provider_type = data.provider_type;
        
        
        if (data.region_policy !== undefined) updatePayload.region_policy = data.region_policy;
        
        
        if (data.supports_streaming !== undefined) updatePayload.supports_streaming = data.supports_streaming;
        
        
        if (data.supports_tools !== undefined) updatePayload.supports_tools = data.supports_tools;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        
        if (data.api_keys !== undefined) {
            await llm_providers.setApi_keys(data.api_keys, { transaction });
        }
        
        if (data.models !== undefined) {
            await llm_providers.setModels(data.models, { transaction });
        }
        

        

        return llm_providers;
    }

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

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

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


        return llm_providers;
    }

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

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

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

        await llm_providers.destroy({
            transaction
        });

        return llm_providers;
    }

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

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

        if (!llm_providers) {
            return llm_providers;
        }

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

        
        
        
        
        
        
        
        
        
        output.llm_models_provider = await llm_providers.getLlm_models_provider({
            transaction
        });
        
        
        output.llm_api_keys_provider = await llm_providers.getLlm_api_keys_provider({
            transaction
        });
        
        
        output.key_rotation_policies_provider = await llm_providers.getKey_rotation_policies_provider({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.api_keys = await llm_providers.getApi_keys({
            transaction
        });
        
        
        output.models = await llm_providers.getModels({
            transaction
        });
        
        
        output.organizations = await llm_providers.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',
        
      },


      {
        model: db.llm_api_keys,
        as: 'api_keys',
        required: false,
      },

      {
        model: db.llm_models,
        as: 'models',
        required: false,
      },


    ];

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

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

            
            

            

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

            
            if (filter.provider_type) {
                where = {
                    ...where,
                provider_type: filter.provider_type,
            };
            }
            
            if (filter.region_policy) {
                where = {
                    ...where,
                region_policy: filter.region_policy,
            };
            }
            
            if (filter.supports_streaming) {
                where = {
                    ...where,
                supports_streaming: filter.supports_streaming,
            };
            }
            
            if (filter.supports_tools) {
                where = {
                    ...where,
                supports_tools: filter.supports_tools,
            };
            }
            
            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.api_keys) {
        const searchTerms = filter.api_keys.split('|');

        include = [
          {
            model: db.llm_api_keys,
            as: 'api_keys_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  label: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.models) {
        const searchTerms = filter.models.split('|');

        include = [
          {
            model: db.llm_models,
            as: 'models_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

        const records = await db.llm_providers.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,
        }));
    }

    
};

