package cz.moneta.test.regression.cvm.api.cvm;

import com.fasterxml.jackson.databind.JsonNode;
import cz.moneta.test.dsl.Harness;
import cz.moneta.test.harness.annotations.TestCase;
import cz.moneta.test.harness.annotations.TestScenario;
import cz.moneta.test.harness.support.rest.RawRestRequest;
import org.jooq.Record;
import org.jooq.Result;
import org.junit.jupiter.api.Assertions;

import java.time.Instant;
import java.util.List;

import static cz.moneta.test.harness.annotations.Environment.PPE;
import static cz.moneta.test.harness.annotations.Environment.TST1;

@TestScenario(name = "Call API RTRD_SAVE_APP_SAVE_REST to WSO2 and assert response parameters")
public class ApiRtrdSaveAppSaveRest {

    @TestCase(name = "Call API RTRD_SAVE_APP_SAVE_REST to WSO2", environments = {TST1, PPE})
    public void postRtrdSaveAppSaveRest(Harness harness) throws InterruptedException {
        RawRestRequest.Response response = harness.tasks().wso2().restRequest().prepareRequestFromCvm(
                "cvm.cluster/RTRD_SAVE_APP_SAVE_REST/001", false,
                "{ \"birthNumber\": \"string\",\n" +
                        "  \"changeDate\": \"" + Instant.now() + "\",\n" +
                        "  \"channelId\": \"SBA\",\n" +
                        "  \"cif\": \"string\",\n" +
                        "  \"ico\": \"string\",\n" +
                        "  \"key\": 76589,\n" +
                        "  \"productClass\": \"50\",\n" +
                        "  \"signDate\": \"" + Instant.now() + "\",\n" +
                        "  \"state\": \"9\",\n" +
                        "  \"subtypeId\": \"Sc\",\n" +
                        "  \"typeId\": \"Sc\",\n" +
                        "  \"id\": \"12\",\n" +
                        "  \"loanAmount\": 0,\n" +
                        "  \"uniPtKey\": \"78279459666\"\n" +
                        "}")
                .postExtended()
                .andAssertStatus(200);

        JsonNode result = response.extract("result");
        List<Object> activityIds = response.getHeader("activityId");

        Assertions.assertNotNull(result, "Not found result in response");
        Assertions.assertEquals("OK", result.textValue(), "Not found OK in result in response");
        Assertions.assertEquals(1, activityIds.size(), "API should return activityId header");

        Thread.sleep(2000); // Delay to finish async code

        Result<Record> onlineDbRecords = harness.tasks().cvm().onlineDbGetData().getOnlineData(
                "RTRD_NAS_APP_SAVE", activityIds.get(0).toString());
        Assertions.assertEquals(14, onlineDbRecords.size(), "Should create 14 records in OnlineDB");

    }
}