package cz.moneta.test.harness.endpoints.hypos.hyposdb;

import cz.moneta.test.harness.connectors.database.MsSqlConnector;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.Endpoint;
import cz.moneta.test.harness.support.auth.AuthSupport;
import cz.moneta.test.harness.support.auth.Credentials;
import org.jooq.Record;
import org.jooq.Result;

import java.util.Optional;

public class HyposDbEndpoint implements Endpoint {

    private final StoreAccessor store;
    private final ThreadLocal<MsSqlConnector> hyposDbConnector = ThreadLocal.withInitial(this::initConnector);
    private static final String endpointName = "endpoints.hyposdb.url";

    public HyposDbEndpoint(StoreAccessor store) {
        this.store = store;
    }

    public Result<Record> executeSql(String sql) {
        return hyposDbConnector.get().executeSql(sql);
    }

    private MsSqlConnector initConnector() {
        String credentialsValue = "hypos-db";
        Optional<String> configEndpointValue = Optional.ofNullable(store.getConfig(endpointName));

        return configEndpointValue.map(url -> {
            if (AuthSupport.hasCredentials(credentialsValue, store)) {
                Credentials credentials = AuthSupport.getCredentials(credentialsValue, store);
                return new MsSqlConnector(url, credentials);
            }

            return new MsSqlConnector(url);
        }).orElseThrow(() -> new IllegalStateException("You need to configure " + endpointName + " to work with Hypos Database"));
    }
}