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

import com.yandex.direct.api.v5.campaignsext.SuspendRequest
import com.yandex.direct.api.v5.campaignsext.SuspendResponse
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.campaignsext.validation.CampaignsExtSuspendResumeRequestValidator
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 SuspendCampaignsExtDelegate @Autowired constructor(
    auth: ApiAuthenticationSource,
    private val campaignService: CampaignService,
    private val requestValidator: CampaignsExtSuspendResumeRequestValidator,
    private val resultConverter: ResultConverter,
    ppcPropertiesSupport: PpcPropertiesSupport,
    featureService: FeatureService
) : OperationOnListDelegate<SuspendRequest, SuspendResponse, Long, Long>(
    ApiPathConverter.forCampaigns(), auth, ppcPropertiesSupport, featureService
) {
    companion object {
        private val logger = LoggerFactory.getLogger(SuspendCampaignsExtDelegate::class.java)
    }

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

    override fun convertRequest(externalRequest: SuspendRequest): 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.suspendCampaigns(validItems, getOperatorUid(), getClientId())
        return resultConverter.toApiMassResultRespectingPath(result, DEFECT_PRESENTATIONS_RESPECTING_PATH)
    }

    override fun convertResponse(result: ApiResult<List<ApiResult<Long?>>>): SuspendResponse =
        SuspendResponse().withSuspendResults(resultConverter.toActionResults(result, apiPathConverter))

    private fun getClientId() = auth.chiefSubclient.clientId

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