import { IoAdapter } from '@nestjs/platform-socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';
import { INestApplication } from '@nestjs/common';
import {
    getRedisHost,
    getRedisPassword,
    getRedisPort,
    isRedisTlsEnabled,
} from '../services/redis/redis.config';

export class RedisIoAdapter extends IoAdapter {
    private adapterConstructor: ReturnType<typeof createAdapter>;

    constructor(app: INestApplication) {
        super(app);
    }

    async connectToRedis(): Promise<void> {
        const host = getRedisHost();
        const port = getRedisPort();
        const socket = isRedisTlsEnabled()
            ? { host, port, tls: true as const }
            : { host, port };

        const pubClient = createClient({
            socket,
            password: getRedisPassword(),
        });

        const subClient = pubClient.duplicate();

        await pubClient.connect();
        await subClient.connect();

        this.adapterConstructor = createAdapter(pubClient, subClient);
    }

    createIOServer(port: number, options?: any): any {
        const server = super.createIOServer(port, options);
        server.adapter(this.adapterConstructor);
        return server;
    }
}
