import { Module, type OnApplicationShutdown, Inject } from '@nestjs/common';
import { createQueue, type QueueHandle } from '@mosaicstack/queue';
import { SessionGCService } from './session-gc.service.js';
import { REDIS } from './gc.tokens.js';

const GC_QUEUE_HANDLE = 'GC_QUEUE_HANDLE';

@Module({
  providers: [
    {
      provide: GC_QUEUE_HANDLE,
      useFactory: (): QueueHandle => {
        return createQueue();
      },
    },
    {
      provide: REDIS,
      useFactory: (handle: QueueHandle) => handle.redis,
      inject: [GC_QUEUE_HANDLE],
    },
    SessionGCService,
  ],
  exports: [SessionGCService],
})
export class GCModule implements OnApplicationShutdown {
  constructor(@Inject(GC_QUEUE_HANDLE) private readonly handle: QueueHandle) {}

  async onApplicationShutdown(): Promise<void> {
    await this.handle.close().catch(() => {});
  }
}
