import { Router } from 'express';
import { DataSource } from 'typeorm';
import { BranchesService } from './services';
import { BranchesController } from './controllers';
import { Branch, UserBranchAssignment, BranchSchedule, BranchPaymentTerminal } from './entities';

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

export class BranchesModule {
  public router: Router;
  public branchesService: BranchesService;
  private dataSource: DataSource;
  private basePath: string;

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

  private initializeServices(): void {
    const branchRepository = this.dataSource.getRepository(Branch);
    const assignmentRepository = this.dataSource.getRepository(UserBranchAssignment);
    const scheduleRepository = this.dataSource.getRepository(BranchSchedule);
    const terminalRepository = this.dataSource.getRepository(BranchPaymentTerminal);

    this.branchesService = new BranchesService(
      branchRepository,
      assignmentRepository,
      scheduleRepository,
      terminalRepository
    );
  }

  private initializeRoutes(): void {
    const branchesController = new BranchesController(this.branchesService);
    this.router.use(`${this.basePath}/branches`, branchesController.router);
  }

  static getEntities(): Function[] {
    return [Branch, UserBranchAssignment, BranchSchedule, BranchPaymentTerminal];
  }
}
