import { Router } from 'express';
import { DataSource } from 'typeorm';
import { StorageService } from './services';
import { StorageController } from './controllers';
import {
  StorageBucket,
  StorageFolder,
  StorageFile,
} from './entities';

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

export class StorageModule {
  public router: Router;
  public storageService: StorageService;
  private dataSource: DataSource;
  private basePath: string;

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

  private initializeServices(): void {
    const bucketRepository = this.dataSource.getRepository(StorageBucket);
    const folderRepository = this.dataSource.getRepository(StorageFolder);
    const fileRepository = this.dataSource.getRepository(StorageFile);

    this.storageService = new StorageService(
      bucketRepository,
      folderRepository,
      fileRepository
    );
  }

  private initializeRoutes(): void {
    const storageController = new StorageController(this.storageService);
    this.router.use(`${this.basePath}/storage`, storageController.router);
  }

  static getEntities(): Function[] {
    return [
      StorageBucket,
      StorageFolder,
      StorageFile,
    ];
  }
}
