package ru.yandex.direct.api.v5.entity.campaigns.delegate

import com.yandex.direct.api.v5.campaigns.ResumeRequest
import com.yandex.direct.api.v5.campaigns.ResumeResponse
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import ru.yandex.direct.api.v5.common.ApiPathConverter
import ru.yandex.direct.api.v5.converter.ResultConverter
import ru.yandex.direct.api.v5.entity.OperationOnListDelegate
import ru.yandex.direct.api.v5.entity.campaigns.CampaignsEndpoint.DEFECT_PRESENTATIONS_RESPECTING_PATH
import ru.yandex.direct.api.v5.entity.campaigns.validation.CampaignsSuspendResumeRequestValidator
import ru.yandex.direct.api.v5.result.ApiMassResult
import ru.yandex.direct.api.v5.result.ApiResult
import ru.yandex.direct.api.v5.security.ApiAuthenticationSource
import ru.yandex.direct.api.v5.validation.DefectType
import ru.yandex.direct.common.db.PpcPropertiesSupport
import ru.yandex.direct.core.entity.campaign.service.CampaignService
import ru.yandex.direct.core.entity.feature.service.FeatureService
import ru.yandex.direct.validation.result.ValidationResult

@Service
class ResumeCampaignsDelegate @Autowired constructor(
    auth: ApiAuthenticationSource,
    private val campaignService: CampaignService,
    private val requestValidator: CampaignsSuspendResumeRequestValidator,
    private val resultConverter: ResultConverter,
    ppcPropertiesSupport: PpcPropertiesSupport,
    featureService: FeatureService
) : OperationOnListDelegate<ResumeRequest, ResumeResponse, Long, Long>(
    ApiPathConverter.forCampaigns(), auth, ppcPropertiesSupport, featureService
) {
    companion object {
        private val logger = LoggerFactory.getLogger(ResumeCampaignsDelegate::class.java)
    }

    override fun validateRequest(externalRequest: ResumeRequest): ValidationResult<ResumeRequest, DefectType> =
        requestValidator.validateExternalRequest(externalRequest)

    override fun convertRequest(externalRequest: ResumeRequest): List<Long> =
        externalRequest.selectionCriteria.ids

    override fun validateInternalRequest(internalRequest: List<Long>): ValidationResult<List<Long>, DefectType> =
        requestValidator.validateInternalRequest(internalRequest)

    override fun processList(validItems: List<Long>): ApiMassResult<Long> {
        logger.debug("process request: {}", validItems)
        val result = campaignService.resumeCampaigns(validItems, getOperatorUid(), getClientId())
        return resultConverter.toApiMassResultRespectingPath(result, DEFECT_PRESENTATIONS_RESPECTING_PATH)
    }

    override fun convertResponse(result: ApiResult<List<ApiResult<Long>>>): ResumeResponse =
        ResumeResponse().withResumeResults(resultConverter.toActionResults(result, apiPathConverter))

    private fun getClientId() = auth.chiefSubclient.clientId

    private fun getOperatorUid() = auth.operator.uid
}
