import { Global, Module } from "@nestjs/common";
import { BullModule } from "@nestjs/bullmq";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { QUEUE_NAMES } from "./queue.constants";

function parseRedisConnection(redisUrl: string) {
  try {
    const url = new URL(redisUrl);
    const isTls = url.protocol === "rediss:";
    const db = url.pathname && url.pathname !== "/" ? Number(url.pathname.slice(1)) : undefined;
    return {
      host: url.hostname,
      port: Number(url.port || (isTls ? 6380 : 6379)),
      password: url.password || undefined,
      ...(db !== undefined ? { db } : {}),
      ...(isTls ? { tls: {} } : {}),
    } as Record<string, unknown>;
  } catch {
    return { host: "localhost", port: 6379 } as Record<string, unknown>;
  }
}

@Global()
@Module({
  imports: [
    ConfigModule,
    BullModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        connection: parseRedisConnection(config.get<string>("REDIS_URL", "redis://localhost:6379")),
      }),
    }),
    BullModule.registerQueue(
      { name: QUEUE_NAMES.EMAIL },
      { name: QUEUE_NAMES.PROVISIONING },
      { name: QUEUE_NAMES.RECONCILE },
      { name: QUEUE_NAMES.SIM_MANAGEMENT }
    ),
  ],
  exports: [BullModule],
})
export class QueueModule {}
