import { SimulationCategory } from '@agiliza/api/domain'
import { Configuration, DominioApi } from '@microcredito/client'

import { ErrorMappers, SimulationMappers } from '../../mappers'
import { API_URL, mapUserAgentToString, UserAgent } from '../shared'

export interface SimulationContextRepository {
  fetchSimulationCategories(): Promise<SimulationCategory[]>
}

export class SimulationContextRepositoryImpl implements SimulationContextRepository {
  private api: DominioApi
  private simulationCategoryMapper: SimulationMappers.SimulationCategoryMapper
  private errorAdapter: ErrorMappers.ResponseErrorAdapter

  constructor(userAgent: string) {
    this.errorAdapter = new ErrorMappers.ResponseErrorAdapter()
    this.simulationCategoryMapper = new SimulationMappers.SimulationCategoryMapper()
    this.api = new DominioApi(
      new Configuration({
        basePath: API_URL,
        headers: {
          'User-Agent': userAgent,
        },
      })
    )
  }

  public fetchSimulationCategories = async (): Promise<SimulationCategory[]> => {
    try {
      const result = await this.api.obterCategoriasSimulacao()
      return result.map(this.simulationCategoryMapper.mapApiModelToDomain)
    } catch (e) {
      const result = await this.errorAdapter.mapApiModelToDomain(e)
      throw result
    }
  }
}

export class SimulationContextRepositoryImplFactory {
  static create(userAgent: UserAgent) {
    const repository = new SimulationContextRepositoryImpl(mapUserAgentToString(userAgent))
    return repository
  }
}
