import { RequestValidator } from './RequestValidator';
import { DomainEvent } from '@domain/DomainEvent';

export abstract class UseCase<DTO, RESPONSE = any> {
  protected events: DomainEvent[] = [];

  validator: RequestValidator | null = null;

  protected abstract implementation(req: DTO): Promise<RESPONSE>;

  public execute = async (req: DTO) => {
    let result: any;

    if (this.validator) {
      result = await this.implementation(this.validator.validate(req));
    } else {
      result = await this.implementation(req);
    }

    this.events.forEach((e: DomainEvent) => {
      e.execute(req, result);
    });

    return result;
  };
}
