package dp.kotul.templategroupsbackend.facade

import dp.kotul.starter.service.AuthorizationService
import dp.kotul.templategroupsbackend.helper.SolrSearchHelper
import dp.kotul.templategroupsbackend.model.entity.VariableSourceType
import dp.kotul.templategroupsbackend.model.response.TemplateVariableBasicResponse
import dp.kotul.templategroupsbackend.repository.TemplateRepository
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional

interface TemplateVariableFacade {
    fun getTemplateVariables(templateId: Int, laeId: Int?): List<TemplateVariableBasicResponse>
}

@Component
@Transactional
class TemplateVariableFacadeImpl(
        val authService: AuthorizationService,
        val templateRepository: TemplateRepository,
        val solrSearchHelper: SolrSearchHelper
) : TemplateVariableFacade {

    override fun getTemplateVariables(templateId: Int, laeId: Int?): List<TemplateVariableBasicResponse> {
        val user = authService.getUser()
        val languageId = laeId ?: user.laeId

        val template = templateRepository.findByIdOrNull(templateId) ?: return emptyList()

        val solrTemplatesResponse = solrSearchHelper.getSolrTemplatesResponse(languageId, listOf(template)) ?: return emptyList()

        val withoutTemplateSource = template.templateVariables.filter { it.variableSource?.sourceType != VariableSourceType.TEMPLATE }

        return withoutTemplateSource.map { templateVariable ->
            val templateVariableSolr = solrTemplatesResponse.templates.single().templateVariables.first { it.templateVariableExtId == templateVariable.templateVariableExtId }
            TemplateVariableBasicResponse(templateVariableId = templateVariable.templateVariableId,
                    templateVariableExtId = templateVariableSolr.templateVariableExtId,
                    name = templateVariableSolr.name,
                    templateVariableExtType = templateVariableSolr.templateVariableExtType)
        }
    }
}
