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

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

        const llm_api_keys = await db.llm_api_keys.create(
            {
                id: data.id || undefined,
        
        label: data.label
        ||
        null
            ,
            
        key_fingerprint: data.key_fingerprint
        ||
        null
            ,
            
        key_status: data.key_status
        ||
        null
            ,
            
        last_rotated_at: data.last_rotated_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        is_primary: data.is_primary
        ||
        false
        
            ,
            
        requests_per_minute_limit: data.requests_per_minute_limit
        ||
        null
            ,
            
        daily_request_limit: data.daily_request_limit
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return llm_api_keys;
    }
    

    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_api_keysData = data.map((item, index) => ({
                id: item.id || undefined,
                
                label: item.label
            ||
            null
            ,
            
                key_fingerprint: item.key_fingerprint
            ||
            null
            ,
            
                key_status: item.key_status
            ||
            null
            ,
            
                last_rotated_at: item.last_rotated_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                is_primary: item.is_primary
            ||
            false
        
            ,
            
                requests_per_minute_limit: item.requests_per_minute_limit
            ||
            null
            ,
            
                daily_request_limit: item.daily_request_limit
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return llm_api_keys;
    }

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


        

        const updatePayload = {};
        
        if (data.label !== undefined) updatePayload.label = data.label;
        
        
        if (data.key_fingerprint !== undefined) updatePayload.key_fingerprint = data.key_fingerprint;
        
        
        if (data.key_status !== undefined) updatePayload.key_status = data.key_status;
        
        
        if (data.last_rotated_at !== undefined) updatePayload.last_rotated_at = data.last_rotated_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.is_primary !== undefined) updatePayload.is_primary = data.is_primary;
        
        
        if (data.requests_per_minute_limit !== undefined) updatePayload.requests_per_minute_limit = data.requests_per_minute_limit;
        
        
        if (data.daily_request_limit !== undefined) updatePayload.daily_request_limit = data.daily_request_limit;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return llm_api_keys;
    }

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

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

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


        return llm_api_keys;
    }

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

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

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

        await llm_api_keys.destroy({
            transaction
        });

        return llm_api_keys;
    }

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

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

        if (!llm_api_keys) {
            return llm_api_keys;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.provider = await llm_api_keys.getProvider({
            transaction
        });
        
        
        output.organizations = await llm_api_keys.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.label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'llm_api_keys',
                        'label',
                        filter.label,
                    ),
                };
            }
            
            if (filter.key_fingerprint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'llm_api_keys',
                        'key_fingerprint',
                        filter.key_fingerprint,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.key_status) {
                where = {
                    ...where,
                key_status: filter.key_status,
            };
            }
            
            if (filter.is_primary) {
                where = {
                    ...where,
                is_primary: filter.is_primary,
            };
            }
            


      

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

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

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

    
};

