package dp.kotul.templategroupsbackend.facade

import dp.kotul.solrapimodel.SolrApiSearchParameters
import dp.kotul.solrapimodel.solrsearch.AssetType.TEMPLATE
import dp.kotul.starter.filter.RequestCorrelation
import dp.kotul.starter.service.AuthorizationService
import dp.kotul.templategroupsbackend.client.SolrApiClient
import dp.kotul.templategroupsbackend.model.solrsearch.SolrSearchRequest
import dp.kotul.templategroupsbackend.model.solrsearch.template.TemplateSolrResponse
import org.springframework.stereotype.Component
import org.springframework.util.MultiValueMap

interface TemplateFacade {
    fun getTemplatesSolr(solrSearchRequest: SolrSearchRequest): TemplateSolrResponse?
}

@Component
class TemplateFacadeImpl(
        val authService: AuthorizationService,
        val solrApiClient: SolrApiClient
) : TemplateFacade {
    override fun getTemplatesSolr(solrSearchRequest: SolrSearchRequest): TemplateSolrResponse? {
        val accessToken = authService.getValidAuthorizationHeader()
        val user = authService.getUser()

        val correlationId = RequestCorrelation.getId()
        val languageId = solrSearchRequest.laeId ?: user.laeId

        return solrApiClient.getSolrTemplatesResponse(accessToken, correlationId, languageId,
            SolrApiSearchParameters(
                q = "\"${solrSearchRequest.searchText}\"",
                fq = "+assetType:${TEMPLATE.value}",
                fl = null,
                sort = listOf("${solrSearchRequest.sortBy} ${solrSearchRequest.sort}"),
                start = solrSearchRequest.start,
                rows = solrSearchRequest.rows)
        )
    }
}
