package cz.moneta.test.harness.endpoints.testautomationdb;

import cz.moneta.test.harness.connectors.database.PostgresConnector;
import cz.moneta.test.harness.constants.HarnessConfigConstants;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.CommonEndpoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jooq.Record;
import org.jooq.Result;

import java.util.Optional;

public class TestAutomationDbEndpoint extends CommonEndpoint {

    // Logins to DB must be here because of local test runs
    private static final String NAME = "cli_creator";
    private static final String PASS = "dkGkl8_7XcTJfLqm1G";
    private static final String INSERT_CREATED_CLIENT_SQL = "INSERT INTO created_clients_log (cif, birth_number, ico, environment, time_created, created_by, test_case, platform, jenkins, grid_node) " +
            "VALUES ('#CLIENT_CIF', '#BIRTH_NUMBER', #ICO, '#ENVIRONMENT', '#TTME_CREATED', '#CREATED_BY', '#TEST_CASE', '#PLATFORM', #JENKINS, #GRID_NODE)";

    private final ThreadLocal<PostgresConnector> testAutomationDdConnector = ThreadLocal.withInitial(this::initConnector);

    private final StoreAccessor storeAccessor;

    private static final Logger logger = LogManager.getLogger(TestAutomationDbEndpoint.class);

    public TestAutomationDbEndpoint(StoreAccessor storeAccessor) {
        super(storeAccessor);
        this.storeAccessor = storeAccessor;
    }

    public Result<Record> executeSql(String sqlToExecute) {
        return testAutomationDdConnector.get().executeSql(sqlToExecute);
    }

    public void insertCreatedClientInfo(String cif, String birthNumber, String ico, String dateTimeCreated, String bankerUsername, String platform, String gridNode) {
        String sqlToExecute = INSERT_CREATED_CLIENT_SQL.replace("#CLIENT_CIF", cif)
                .replace("#BIRTH_NUMBER", birthNumber)
                .replace("#ICO", handlePossibleNullValue(ico))
                .replace("#ENVIRONMENT", getEnvironment().getJiraAlias())
                .replace("#TTME_CREATED", dateTimeCreated)
                .replace("#CREATED_BY", bankerUsername)
                .replace("#TEST_CASE", storeAccessor.getGlobal(HarnessConfigConstants.TEST_UNIQUE_ID))
                .replace("#PLATFORM", platform)
                .replace("#JENKINS", getRunOnJenkinsValue())
                .replace("#GRID_NODE", handlePossibleNullValue(gridNode));

        this.executeSql(sqlToExecute);

        logger.info("Created client data logged in Test Automation Database. Executed sql: " + sqlToExecute);
    }

    private String handlePossibleNullValue(String value) {
        return value == null ? "null" : "'" + value + "'";
    }

    private String getRunOnJenkinsValue() {
        boolean runOnJenkins = storeAccessor.getConfig(HarnessConfigConstants.JENKINS_BUILD_URL) != null;
        return Boolean.toString(runOnJenkins);
    }

    private PostgresConnector initConnector() {
        String endpointUrl = "endpoints.testautomationdb.url";
        return Optional.ofNullable(storeAccessor.getConfig(endpointUrl))
                .map(url -> new PostgresConnector(url, NAME, PASS))
                .orElseThrow(() -> new IllegalStateException("You need to configure " + endpointUrl + " to work with Test Automation Database"));
    }
}
