import { Router } from 'express';
import { DataSource } from 'typeorm';
import { NotificationsService } from './services';
import { NotificationsController } from './controllers';
import {
  Channel,
  NotificationTemplate,
  NotificationTemplateTranslation,
  NotificationPreference,
  Notification,
  NotificationBatch,
  InAppNotification,
} from './entities';

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

export class NotificationsModule {
  public router: Router;
  public notificationsService: NotificationsService;
  private dataSource: DataSource;
  private basePath: string;

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

  private initializeServices(): void {
    const channelRepository = this.dataSource.getRepository(Channel);
    const templateRepository = this.dataSource.getRepository(NotificationTemplate);
    const preferenceRepository = this.dataSource.getRepository(NotificationPreference);
    const notificationRepository = this.dataSource.getRepository(Notification);
    const batchRepository = this.dataSource.getRepository(NotificationBatch);
    const inAppRepository = this.dataSource.getRepository(InAppNotification);

    this.notificationsService = new NotificationsService(
      channelRepository,
      templateRepository,
      preferenceRepository,
      notificationRepository,
      batchRepository,
      inAppRepository
    );
  }

  private initializeRoutes(): void {
    const notificationsController = new NotificationsController(this.notificationsService);
    this.router.use(`${this.basePath}/notifications`, notificationsController.router);
  }

  static getEntities(): Function[] {
    return [
      Channel,
      NotificationTemplate,
      NotificationTemplateTranslation,
      NotificationPreference,
      Notification,
      NotificationBatch,
      InAppNotification,
    ];
  }
}
