import { Router } from 'express';
import { DataSource } from 'typeorm';
import { WhatsAppService } from './services';
import { WhatsAppController } from './controllers';
import {
  WhatsAppAccount,
  WhatsAppContact,
  WhatsAppMessage,
  WhatsAppTemplate,
} from './entities';

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

export class WhatsAppModule {
  public router: Router;
  public whatsappService: WhatsAppService;
  private dataSource: DataSource;
  private basePath: string;

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

  private initializeServices(): void {
    const accountRepository = this.dataSource.getRepository(WhatsAppAccount);
    const contactRepository = this.dataSource.getRepository(WhatsAppContact);
    const messageRepository = this.dataSource.getRepository(WhatsAppMessage);
    const templateRepository = this.dataSource.getRepository(WhatsAppTemplate);

    this.whatsappService = new WhatsAppService(
      accountRepository,
      contactRepository,
      messageRepository,
      templateRepository
    );
  }

  private initializeRoutes(): void {
    const whatsappController = new WhatsAppController(this.whatsappService);
    this.router.use(`${this.basePath}/whatsapp`, whatsappController.router);
  }

  static getEntities(): Function[] {
    return [
      WhatsAppAccount,
      WhatsAppContact,
      WhatsAppMessage,
      WhatsAppTemplate,
    ];
  }
}
