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

import cz.moneta.test.harness.connectors.database.OracleConnector;
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 CdsEndpoint implements Endpoint {

    private final StoreAccessor store;
    private final ThreadLocal<OracleConnector> connector = ThreadLocal.withInitial(this::initConnector);

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

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

    @Override
    public boolean canAccess() {
        return AuthSupport.hasCredentials("cds", store);
    }

    private OracleConnector initConnector() {
        String endpointName = "endpoints.cds.url";
        Credentials credentials = AuthSupport.getCredentials("cds", store);
        return Optional.ofNullable(store.getConfig(endpointName))
                .map(url -> new OracleConnector(url, credentials.getUsername(), credentials.getPassword()))
                .orElseThrow(() -> new IllegalStateException("You need to configure " + endpointName + " to work with CDS"));
    }
}
