import {
  DynamicModule,
  Global,
  Inject,
  Module,
  OnModuleInit,
  Provider,
} from "@nestjs/common";
import { Cache } from "cache-manager";
import { CACHE_MANAGER } from "@nestjs/cache-manager";
import { setCacheConfiguration, setCacheManager } from "./cacheable.helpers";
import { CacheableConfiguration } from "./cacheable.interfaces";
const CACHEABLE_CONFIG = "CACHEABLE_CONFIG";
@Global()
@Module({})
export class CacheableModule implements OnModuleInit {
  constructor(
    @Inject(CACHE_MANAGER) cacheManager: Cache,
    @Inject(CACHEABLE_CONFIG) private readonly config: CacheableConfiguration
  ) {
    setCacheManager(cacheManager);

    //get current provider
  }
  onModuleInit() {
    // Now that everything is initialized, you can safely use your providers
    setCacheConfiguration(this.config);
    console.log(this.config); // Cache manager provider
  }

  static forRootAsync(options: {
    imports: any[];
    useFactory: (
      ...args: any[]
    ) => Promise<CacheableConfiguration> | CacheableConfiguration;
    inject: any[];
  }): DynamicModule {
    const providers: Provider[] = [
      {
        provide: CACHEABLE_CONFIG,
        useFactory: options.useFactory,
        inject: options.inject,
      },
    ];

    return {
      module: CacheableModule,
      imports: options.imports,
      providers: providers,
      exports: providers,
    };
  }
}
