import { createClient } from 'redis';
import consola from 'consola'

export default defineNitroPlugin(async (nitroApp) => {
    return
    const {redis: config} = useRuntimeConfig()
    consola.info('Redis ...');
    const redisConnect = createClient({
        name: config.connectName,
        username: config.username,
        password: config.password,
        database: Number(config.database),
        url: `redis://${config.username}:${config.password}@${config.host}:${config.port}/${config.database}`,
    });
    redisConnect.on('connect', async () => {
        consola.info(`redis://${config.username}:${config.password}@${config.host}:${config.port}/${config.database}`)
        consola.info(await redisConnect.set('SI HI', 'Star Writ'));
    });

    redisConnect.on('error', (err) => {
        // console.log(err)
        // consola.error('Redis error: ', err);
    });

    // 连接到 Redis
    await redisConnect.connect();
    // 将连接池添加到 Nitro 应用上下文
    nitroApp.hooks.hook('request', async (event) => {
        event.context.redis = redisConnect
    })
    nitroApp.hooks.hook('error', async () => {
        redisConnect.disconnect()
    })
})
