

package services.testdata.allocation

import javax.inject.{ Inject, Singleton }
import model.exchange.testdata.CreateCandidateAllocationResponse
import model.testdata.CreateCandidateAllocationData
import play.api.mvc.RequestHeader
import services.allocation.CandidateAllocationService

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import uk.gov.hmrc.http.HeaderCarrier

@Singleton
class CandidateAllocationGenerator @Inject() (candidateAllocationService: CandidateAllocationService) {

  def generate(generationId: Int, createData: CreateCandidateAllocationData)(
    implicit hc: HeaderCarrier, rh: RequestHeader): Future[CreateCandidateAllocationResponse] = {

    candidateAllocationService.getCandidateAllocations(createData.eventId, createData.sessionId).flatMap { existingAllocation =>

      val newAllocations = createData.toCandidateAllocations

      val newAllocationsWithVersion = if(newAllocations.version.isEmpty) {
        newAllocations.copy(version = existingAllocation.version.getOrElse(""))
      } else {
        createData.toCandidateAllocations
      }

      candidateAllocationService.allocateCandidates(newAllocationsWithVersion, append = true).map { d =>
        CreateCandidateAllocationResponse(generationId, createData.copy(version = d.version))
      }
    }
  }
}
