import { Router } from 'express';
import { DataSource } from 'typeorm';
import { AuditService } from './services';
import { AuditController } from './controllers';
import {
  AuditLog,
  EntityChange,
  LoginHistory,
  SensitiveDataAccess,
  DataExport,
  PermissionChange,
  ConfigChange,
} from './entities';

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

export class AuditModule {
  public router: Router;
  public auditService: AuditService;
  private dataSource: DataSource;
  private basePath: string;

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

  private initializeServices(): void {
    const auditLogRepository = this.dataSource.getRepository(AuditLog);
    const entityChangeRepository = this.dataSource.getRepository(EntityChange);
    const loginHistoryRepository = this.dataSource.getRepository(LoginHistory);
    const sensitiveDataAccessRepository = this.dataSource.getRepository(SensitiveDataAccess);
    const dataExportRepository = this.dataSource.getRepository(DataExport);
    const permissionChangeRepository = this.dataSource.getRepository(PermissionChange);
    const configChangeRepository = this.dataSource.getRepository(ConfigChange);

    this.auditService = new AuditService(
      auditLogRepository,
      entityChangeRepository,
      loginHistoryRepository,
      sensitiveDataAccessRepository,
      dataExportRepository,
      permissionChangeRepository,
      configChangeRepository
    );
  }

  private initializeRoutes(): void {
    const auditController = new AuditController(this.auditService);
    this.router.use(`${this.basePath}/audit`, auditController.router);
  }

  static getEntities(): Function[] {
    return [
      AuditLog,
      EntityChange,
      LoginHistory,
      SensitiveDataAccess,
      DataExport,
      PermissionChange,
      ConfigChange,
    ];
  }
}
