package cz.moneta.test.dsl.udebs.smeonboarding;

import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.udebs.UdebsEndpoint;
import cz.moneta.test.harness.exception.HarnessException;

import java.util.Optional;

public class SmsKeyBuilder {

    private final StoreAccessor harness;

    private static final String GET_VERIFICATION_SMS_SMEONBOARDING = "select no.otp_code\n" +
            "from udebsge.ntb_otp no\n" +
            "left join udebsge.ntb_transaction nt on no.ntb_transaction_id = no.ntb_transaction_id\n" +
            "left join udebsge.ntb_personal_data pd on pd.ntb_transaction_id = no.ntb_transaction_id\n" +
            "where pd.phone = '%s'\n" +
            "order by no.created desc\n" +
            "fetch first row only";

    public SmsKeyBuilder(StoreAccessor harness) {
        this.harness = harness;
    }

    public String getSmsKeyVerification(String phoneNumber) {
        //FIXME remove after SQL polling is done: TA-872
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //FIXME: add polling until: TA-872
        return Optional.of(harness.getEndpoint(UdebsEndpoint.class))
                .map(e -> e.executeSql(String.format(GET_VERIFICATION_SMS_SMEONBOARDING, phoneNumber)))
                .flatMap(rs -> rs.stream().findFirst())
                .map(r -> r.getValue(0, String.class))
                .orElseThrow(() -> new HarnessException("Error getting GET_VERIFICATION_SMS_SMEONBOARDING from UDEBS."));
    }

}
