package ru.yandex.direct.api.v5.entity.changes.delegate;

import java.util.List;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;

import com.yandex.direct.api.v5.changes.CheckRequest;
import com.yandex.direct.api.v5.changes.CheckResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.direct.api.v5.entity.BaseApiServiceDelegate;
import ru.yandex.direct.api.v5.entity.changes.converter.ChangesCommonConvertUtil;
import ru.yandex.direct.api.v5.entity.changes.validation.CheckValidator;
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.core.entity.changes.model.CheckIntReq;
import ru.yandex.direct.core.entity.changes.model.CheckIntResp;
import ru.yandex.direct.core.entity.changes.service.CheckService;
import ru.yandex.direct.dbutil.model.ClientId;
import ru.yandex.direct.validation.result.PathConverter;
import ru.yandex.direct.validation.result.ValidationResult;

@Component
@ParametersAreNonnullByDefault
public class CheckDelegate extends BaseApiServiceDelegate<CheckRequest, CheckResponse, CheckIntReq, CheckIntResp> {

    private static final Logger logger = LoggerFactory.getLogger(CheckCampaignsDelegate.class);

    private final CheckService checkService;

    @Autowired
    public CheckDelegate(
            ApiAuthenticationSource auth,
            CheckService checkService
    ) {
        super(PathConverter.identity(), auth);
        this.checkService = checkService;
    }

    @Nullable
    @Override
    public ValidationResult<CheckRequest, DefectType> validateRequest(CheckRequest externalRequest) {
        return new CheckValidator().apply(externalRequest);
    }

    @Override
    public CheckIntReq convertRequest(CheckRequest externalRequest) {
        return ChangesCommonConvertUtil.convertCheckRequest(externalRequest);
    }

    @Override
    public ApiResult<List<CheckIntResp>> processRequest(CheckIntReq internalRequest) {
        Long operatorUid = auth.getOperator().getUid();
        ClientId clientId = auth.getSubclient().getClientId();

        CheckIntResp result = checkService.processInternalRequest(operatorUid, clientId, internalRequest);

        return ApiResult.successful(List.of(result));
    }

    @Override
    public CheckResponse convertResponse(ApiResult<List<CheckIntResp>> result) {
        return ChangesCommonConvertUtil.convertCheckResult(result.getResult().get(0));
    }
}
