package dp.kotul.solrapiapplication.facade

import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import dp.kotul.solrapiapplication.client.SolrClient
import dp.kotul.solrapiapplication.helper.CollectionHelper
import dp.kotul.solrapiapplication.model.SolrRequest
import dp.kotul.solrapiapplication.service.ApiResponseService
import dp.kotul.solrapiapplication.service.SearchParameterService
import dp.kotul.solrapimodel.SolrApiSearchParameters
import org.slf4j.Logger
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Component

interface SolrDocumentFacade {
    fun getDocuments(laeId: Int, searchParameters: SolrApiSearchParameters): ResponseEntity<JsonNode?>
}

@Component
class SolrDocumentFacadeImpl(
    val apiResponseService: ApiResponseService,
    val searchParameterService: SearchParameterService,
    val collectionHelper: CollectionHelper,
    val solrClient: SolrClient,
    val mapper: ObjectMapper,
    val log: Logger
) : SolrDocumentFacade {

    override fun getDocuments(laeId: Int, searchParameters: SolrApiSearchParameters): ResponseEntity<JsonNode?> {
        val collection = collectionHelper.getCollection(laeId)
        val parameters = searchParameterService.processParameters(searchParameters)

        log.info("Selecting documents in $collection with parameters: ${mapper.writeValueAsString(searchParameters)}")

        val solrResponse = solrClient.select(collection, SolrRequest(parameters))
        return apiResponseService.getSelectResponseEntity(solrResponse)
    }
}
