import type { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type {
  GetAllRacesPageDataResult,
  GetAllRacesPageDataErrorCode,
} from '@core/racing/application/use-cases/GetAllRacesPageDataUseCase';
import type { AllRacesPageDTO } from '../dtos/AllRacesPageDTO';

export type AllRacesPageDataResponseModel = AllRacesPageDTO;

export type GetAllRacesPageDataApplicationError = ApplicationErrorCode<
  GetAllRacesPageDataErrorCode,
  { message: string }
>;

export class AllRacesPageDataPresenter {
  private model: AllRacesPageDataResponseModel | null = null;

  reset(): void {
    this.model = null;
  }

  present(
    result: Result<GetAllRacesPageDataResult, GetAllRacesPageDataApplicationError>,
  ): void {
    if (result.isErr()) {
      const error = result.unwrapErr();
      throw new Error(error.details?.message ?? 'Failed to get all races page data');
    }

    const output = result.unwrap();

    this.model = {
      races: output.races,
      filters: output.filters,
    };
  }

  getResponseModel(): AllRacesPageDataResponseModel | null {
    return this.model;
  }

  get responseModel(): AllRacesPageDataResponseModel {
    if (!this.model) {
      throw new Error('Presenter not presented');
    }

    return this.model;
  }

  get viewModel(): AllRacesPageDataResponseModel {
    return this.responseModel;
  }
}
