
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,
        
        name: data.name
        ||
        null
            ,
            
        provider: data.provider
        ||
        null
            ,
            
        model_name: data.model_name
        ||
        null
            ,
            
        base_url: data.base_url
        ||
        null
            ,
            
        default_config: data.default_config
        ||
        null
            ,
            
        typical_latency_ms: data.typical_latency_ms
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { 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,
                
                name: item.name
            ||
            null
            ,
            
                provider: item.provider
            ||
            null
            ,
            
                model_name: item.model_name
            ||
            null
            ,
            
                base_url: item.base_url
            ||
            null
            ,
            
                default_config: item.default_config
            ||
            null
            ,
            
                typical_latency_ms: item.typical_latency_ms
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
            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 ai_models = await db.ai_models.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.model_name !== undefined) updatePayload.model_name = data.model_name;
        
        
        if (data.base_url !== undefined) updatePayload.base_url = data.base_url;
        
        
        if (data.default_config !== undefined) updatePayload.default_config = data.default_config;
        
        
        if (data.typical_latency_ms !== undefined) updatePayload.typical_latency_ms = data.typical_latency_ms;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

        await ai_models.update(updatePayload, {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.api_keys_model = await ai_models.getApi_keys_model({
            transaction
        });
        
        
        
        
        output.fill_sessions_ai_model = await ai_models.getFill_sessions_ai_model({
            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 = [



    ];

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

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

            
            

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

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

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

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

            
            if (filter.provider) {
                where = {
                    ...where,
                provider: filter.provider,
            };
            }
            
            if (filter.is_enabled) {
                where = {
                    ...where,
                is_enabled: filter.is_enabled,
            };
            }
            




            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_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'ai_models',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

    
};

