import { Router } from 'express';
import { DataSource } from 'typeorm';
import { FeatureFlagsService } from './services';
import { FeatureFlagsController } from './controllers';
import { Flag, TenantOverride, FlagEvaluation } from './entities';

export interface FeatureFlagsModuleOptions {
  dataSource: DataSource;
  basePath?: string;
}

export class FeatureFlagsModule {
  public router: Router;
  public featureFlagsService: FeatureFlagsService;
  private dataSource: DataSource;
  private basePath: string;

  constructor(options: FeatureFlagsModuleOptions) {
    this.dataSource = options.dataSource;
    this.basePath = options.basePath || '';
    this.router = Router();
    this.initializeServices();
    this.initializeRoutes();
  }

  private initializeServices(): void {
    const flagRepository = this.dataSource.getRepository(Flag);
    const overrideRepository = this.dataSource.getRepository(TenantOverride);

    this.featureFlagsService = new FeatureFlagsService(
      flagRepository,
      overrideRepository
    );
  }

  private initializeRoutes(): void {
    const featureFlagsController = new FeatureFlagsController(this.featureFlagsService);
    this.router.use(`${this.basePath}/feature-flags`, featureFlagsController.router);
  }

  static getEntities(): Function[] {
    return [Flag, TenantOverride, FlagEvaluation];
  }
}
