import { DynamicModule, Global, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LoginCoreModule } from '../../core/login_core/login_core.module';
import { PlayerTaskProgress } from './player_task_progress.entity';
import { TaskProgressDatabaseService } from './task_progress_database.service';
import { TaskProgressMemoryService } from './task_progress_memory.service';
import { TaskService } from './task.service';
import { TasksController } from './tasks.controller';

@Global()
@Module({})
export class TasksModule {
  static forDatabase(): DynamicModule {
    return {
      module: TasksModule,
      global: true,
      imports: [LoginCoreModule, TypeOrmModule.forFeature([PlayerTaskProgress])],
      controllers: [TasksController],
      providers: [
        TaskProgressDatabaseService,
        { provide: 'ITaskProgressStore', useExisting: TaskProgressDatabaseService },
        TaskService,
      ],
      exports: [TaskService, 'ITaskProgressStore'],
    };
  }

  static forMemory(): DynamicModule {
    return {
      module: TasksModule,
      global: true,
      imports: [LoginCoreModule],
      controllers: [TasksController],
      providers: [
        TaskProgressMemoryService,
        { provide: 'ITaskProgressStore', useExisting: TaskProgressMemoryService },
        TaskService,
      ],
      exports: [TaskService, 'ITaskProgressStore'],
    };
  }

  static forRoot(useMemory?: boolean): DynamicModule {
    const shouldUseMemory = useMemory ?? (
      process.env.NODE_ENV === 'test' ||
      process.env.USE_MEMORY_STORAGE === 'true' ||
      !process.env.DB_HOST
    );
    return shouldUseMemory ? this.forMemory() : this.forDatabase();
  }
}
