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

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.sql.CallableStatement;
import java.sql.SQLException;
import java.util.Optional;

public class NasDbEndpoint implements Endpoint {

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

    private final StoreAccessor store;

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

    public void insertUser(String rc, String firstName, String lastName) {
        connector.get().executeStatement(connection -> {
            try {
                CallableStatement call = connection.prepareCall("{ call nasdb_owner.insertuser(?,?,?,?) }");
                call.setString(1, rc);
                call.setString(2, rc);
                call.setString(3, firstName);
                call.setString(4, lastName);
                call.execute();
            } catch (SQLException e) {
                throw new IllegalStateException(
                        String.format("Failed to insert new user (rc: %s, name: %s %s) into NAS DB",
                                rc, firstName, lastName), e);
            }
        });
    }

    public boolean checkPresentIdCardOnBlacklist(String idCard) {
        String sql = "select * from nasdb_owner.blist_lost_id_card d where d.id_card_num = '" + idCard + "'";
        return executeSql(sql).size() > 0 ? true : false;
    }

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

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

    private OracleConnector initConnector() {
        String endpointName = "endpoints.nasdb.url";
        Credentials credentials = AuthSupport.getCredentials("nasdb", 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" +
                        " NAS DB"));
    }
}
