package cz.moneta.test.dsl.udebs;

import cz.moneta.test.dsl.util.PollingUtils;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.udebs.UdebsEndpoint;
import org.jooq.Record;
import org.jooq.Result;

public class AccountMovements {
    private final StoreAccessor harness;

    private final String ACCOUNT_MOVEMENTS = "SELECT * FROM ACCOUNTMOVEMENTS \n" +
            "WHERE ACCOUNTID " +
            "LIKE '%%%s' " +
            "AND PARTNERACCNUM " +
            "LIKE '%%%s' " +
            " AND TRANSACTIONID IS NOT NULL " +
            "ORDER BY TRANSACTIONID DESC " +
            "FETCH FIRST ROW ONLY";

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

    private Result<Record> executeSqlAccountMovements(String... args) {
        return harness.getEndpoint(UdebsEndpoint.class)
                .executeSql(String.format(ACCOUNT_MOVEMENTS, args));
    }

    public double getAmountLastAccountMovement(long waitForResponseInSeconds, String fromAccount, String toAccount, String expectedAmount) {
        String amount = PollingUtils.waitForExpectedResultForSeconds(expectedAmount, waitForResponseInSeconds,
                () -> executeSqlAccountMovements(fromAccount, toAccount)
                        .getValues("AMOUNT")
                        .get(0)
                        .toString());

        return Double.valueOf(amount);
    }
}
