import { Router } from 'express';
import { DataSource } from 'typeorm';
import { PartnersService } from './services';
import { PartnersController } from './controllers';
import { Partner, PartnerAddress, PartnerContact, PartnerBankAccount, PartnerTaxInfo, PartnerSegment } from './entities';

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

export class PartnersModule {
  public router: Router;
  public partnersService: PartnersService;
  private dataSource: DataSource;
  private basePath: string;

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

  private initializeServices(): void {
    const partnerRepository = this.dataSource.getRepository(Partner);
    const addressRepository = this.dataSource.getRepository(PartnerAddress);
    const contactRepository = this.dataSource.getRepository(PartnerContact);
    const bankAccountRepository = this.dataSource.getRepository(PartnerBankAccount);

    this.partnersService = new PartnersService(
      partnerRepository,
      addressRepository,
      contactRepository,
      bankAccountRepository
    );
  }

  private initializeRoutes(): void {
    const partnersController = new PartnersController(this.partnersService);
    this.router.use(`${this.basePath}/partners`, partnersController.router);
  }

  static getEntities(): Function[] {
    return [Partner, PartnerAddress, PartnerContact, PartnerBankAccount, PartnerTaxInfo, PartnerSegment];
  }
}
