import { Module } from '@nestjs/common';
import { Queue } from 'bullmq';
import Redis from 'ioredis';

import { getConfig } from '@hexahost/config';

import { AuthModule } from '../auth/auth.module';
import { AppConfigModule } from '../config/app-config.module';

import { ServerStateService } from './server-state.service';
import {
  REDIS_CLIENT,
  SERVER_LIFECYCLE_QUEUE,
  SERVER_PROVISIONING_QUEUE,
  ServersService,
} from './servers.service';
import { ServersController } from './servers.controller';
import { PlansController } from './plans.controller';
import { PlansService } from './plans.service';

@Module({
  imports: [AppConfigModule, AuthModule],
  controllers: [ServersController, PlansController],
  providers: [
    ServersService,
    ServerStateService,
    PlansService,
    {
      provide: REDIS_CLIENT,
      useFactory: () => {
        const config = getConfig();
        return new Redis(config.REDIS_URL, {
          maxRetriesPerRequest: null,
        });
      },
    },
    {
      provide: SERVER_LIFECYCLE_QUEUE,
      useFactory: () => {
        const config = getConfig();
        return new Queue('server-lifecycle', {
          connection: {
            url: config.REDIS_URL,
            maxRetriesPerRequest: null,
          },
        });
      },
    },
    {
      provide: SERVER_PROVISIONING_QUEUE,
      useFactory: () => {
        const config = getConfig();
        return new Queue('server-provisioning', {
          connection: {
            url: config.REDIS_URL,
            maxRetriesPerRequest: null,
          },
        });
      },
    },
  ],
  exports: [ServersService, REDIS_CLIENT],
})
export class ServersModule {}
