import { CacheTTL, Injectable, Logger } from '@nestjs/common';
import { readFileSync, existsSync } from 'fs';
import { join } from 'path';

@Injectable()
export class DynamicLoader {
  private logger = new Logger(DynamicLoader.name);

  @CacheTTL(60)
  load(
    file: string,
    opts: { path: string; ext: string; parser: (raw: any) => any },
  ): any {
    const fullFileName = join(opts.path, `${file}.${opts.ext}`);
    if (!existsSync(fullFileName)) return null;
    let rawData: any;
    let data: any;
    try {
      rawData = readFileSync(fullFileName, { encoding: 'utf-8' });
      data = opts.parser(rawData);
    } catch (ex) {
      this.logger.error(`Error at config read - ${ex}`);
      return null;
    }
    return data;
  }
}
