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

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.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.Routine;
import org.jooq.TableRecord;

import java.util.Optional;
import java.util.function.Function;

public class AutoDBEndpoint implements Endpoint {

    private final ThreadLocal<OracleConnector> autoDbConnector = ThreadLocal.withInitial(this::initConnector);

    private final StoreAccessor store;

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

    public <R extends TableRecord<R>> R executeDsl(Function<DSLContext, R> query) {
        return autoDbConnector.get().executeDsl(query);
    }

    public <R extends Routine<?>> R executeProcedure(R procedure) {
        return autoDbConnector.get().executeProcedure(procedure);
    }

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

    private OracleConnector initConnector() {
        String endpointName = "endpoints.auto-db.url";
        Credentials credentials = AuthSupport.getCredentials("auto-db", 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 Udebs Database"));
    }

}
