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

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

        const ai_gateways = await db.ai_gateways.create(
            {
                id: data.id || undefined,
        
        gateway_name: data.gateway_name
        ||
        null
            ,
            
        base_url: data.base_url
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        default_model: data.default_model
        ||
        null
            ,
            
        default_daily_request_limit: data.default_daily_request_limit
        ||
        null
            ,
            
        default_daily_cost_limit: data.default_daily_cost_limit
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return ai_gateways;
    }
    

    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_gatewaysData = data.map((item, index) => ({
                id: item.id || undefined,
                
                gateway_name: item.gateway_name
            ||
            null
            ,
            
                base_url: item.base_url
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                default_model: item.default_model
            ||
            null
            ,
            
                default_daily_request_limit: item.default_daily_request_limit
            ||
            null
            ,
            
                default_daily_cost_limit: item.default_daily_cost_limit
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_gateways;
    }

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

        const ai_gateways = await db.ai_gateways.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.gateway_name !== undefined) updatePayload.gateway_name = data.gateway_name;
        
        
        if (data.base_url !== undefined) updatePayload.base_url = data.base_url;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.default_model !== undefined) updatePayload.default_model = data.default_model;
        
        
        if (data.default_daily_request_limit !== undefined) updatePayload.default_daily_request_limit = data.default_daily_request_limit;
        
        
        if (data.default_daily_cost_limit !== undefined) updatePayload.default_daily_cost_limit = data.default_daily_cost_limit;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return ai_gateways;
    }

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

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

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


        return ai_gateways;
    }

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

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

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

        await ai_gateways.destroy({
            transaction
        });

        return ai_gateways;
    }

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

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

        if (!ai_gateways) {
            return ai_gateways;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ai_requests_ai_gateway = await ai_gateways.getAi_requests_ai_gateway({
            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.gateway_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_gateways',
                        'gateway_name',
                        filter.gateway_name,
                    ),
                };
            }
            
            if (filter.base_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_gateways',
                        'base_url',
                        filter.base_url,
                    ),
                };
            }
            
            if (filter.default_model) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_gateways',
                        'default_model',
                        filter.default_model,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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




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

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

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

    
};

