import type { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type {
  ImportRaceResultsApiResult,
  ImportRaceResultsApiErrorCode,
} from '@core/racing/application/use-cases/ImportRaceResultsApiUseCase';
import { ImportRaceResultsSummaryDTO } from '../dtos/ImportRaceResultsSummaryDTO';

export type ImportRaceResultsApiResponseModel = ImportRaceResultsSummaryDTO;

export type ImportRaceResultsApiApplicationError = ApplicationErrorCode<
  ImportRaceResultsApiErrorCode,
  { message: string }
>;

export class ImportRaceResultsApiPresenter {
  private model: ImportRaceResultsApiResponseModel | null = null;

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

  present(
    result: Result<ImportRaceResultsApiResult, ImportRaceResultsApiApplicationError>,
  ): void {
    if (result.isErr()) {
      const error = result.unwrapErr();
      throw new Error(error.details?.message ?? 'Failed to import race results');
    }

    const output = result.unwrap();

    this.model = {
      success: output.success,
      raceId: output.raceId,
      driversProcessed: output.driversProcessed,
      resultsRecorded: output.resultsRecorded,
      errors: output.errors,
    };
  }

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

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

    return this.model;
  }

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