package ru.yandex.qe.dispenser.client.v1.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

import org.apache.cxf.jaxrs.client.WebClient;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import ru.yandex.qe.dispenser.api.v1.request.DiQuotaState;
import ru.yandex.qe.dispenser.api.v1.response.DiResponse;
import ru.yandex.qe.dispenser.client.v1.DiPerson;
import ru.yandex.qe.dispenser.client.v1.builder.SyncRawQuotasRequestBuilder;

/**
 * Factory to build raw quota usage update requests.
 */
final class SyncRawQuotasRequestBuilderImpl implements SyncRawQuotasRequestBuilder {
    @NotNull
    private final String serviceKey;
    @NotNull
    private final Supplier<WebClient> clients;
    @Nullable
    private String reqId;

    @NotNull
    private final List<DiQuotaState> quotaStates = new ArrayList<>();

    SyncRawQuotasRequestBuilderImpl(@NotNull final String serviceKey, @NotNull final Supplier<WebClient> clients) {
        this.serviceKey = serviceKey;
        this.clients = clients;
    }

    @NotNull
    @Override
    public SyncRawQuotasRequestBuilder changeRawQuota(@NotNull final DiQuotaState quotaState) {
        quotaStates.add(quotaState);
        return this;
    }

    @NotNull
    @Override
    public SyncRawQuotasRequestBuilder withReqId(@NotNull final String reqId) {
        this.reqId = reqId;
        return this;
    }

    @NotNull
    @Override
    @TestOnly
    public DiResponse performBy(@NotNull final DiPerson person) {
        return doPerform(WebClientUtils.authenticatePerson(clients.get(), person));
    }

    @NotNull
    @Override
    public DiResponse perform() {
        return doPerform(clients.get());
    }

    @NotNull
    private DiResponse doPerform(@NotNull final WebClient client) {
        return client.path("services/" + serviceKey + "/sync-raw-state/quotas/set")
                .query("reqId", WebClientUtils.actualReqId(reqId))
                .header("X-Req-Id", WebClientUtils.actualReqId(reqId))
                .post(quotaStates, DiResponse.class);
    }
}
