import { Router } from 'express';
import { DataSource } from 'typeorm';
import { WebhooksService } from './services';
import { WebhooksController } from './controllers';
import {
  WebhookEventType,
  WebhookEndpoint,
  WebhookDelivery,
  WebhookEvent,
} from './entities';

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

export class WebhooksModule {
  public router: Router;
  public webhooksService: WebhooksService;
  private dataSource: DataSource;
  private basePath: string;

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

  private initializeServices(): void {
    const eventTypeRepository = this.dataSource.getRepository(WebhookEventType);
    const endpointRepository = this.dataSource.getRepository(WebhookEndpoint);
    const deliveryRepository = this.dataSource.getRepository(WebhookDelivery);
    const eventRepository = this.dataSource.getRepository(WebhookEvent);

    this.webhooksService = new WebhooksService(
      eventTypeRepository,
      endpointRepository,
      deliveryRepository,
      eventRepository
    );
  }

  private initializeRoutes(): void {
    const webhooksController = new WebhooksController(this.webhooksService);
    this.router.use(`${this.basePath}/webhooks`, webhooksController.router);
  }

  static getEntities(): Function[] {
    return [
      WebhookEventType,
      WebhookEndpoint,
      WebhookDelivery,
      WebhookEvent,
    ];
  }
}
