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 MessageMovements {
    private final StoreAccessor harness;

    private final
    String MESSAGE_MOVEMENTS =
            "SELECT * FROM MAILMESSAGES mm " +
                    "INNER JOIN W_MESSAGEBODIES mb ON mm.MESSAGEBODYID = mb.MESSAGEBODYID " +
                    "WHERE mm.FROMCLIENTID = %s " +
                    "ORDER BY mm.BORNDATE DESC " +
                    "FETCH FIRST ROW ONLY";

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

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

    public String getLastMessageMovement(long waitForResponseInSeconds, String clientId, String expectedMessage) {
        return PollingUtils.waitForExpectedResultForSeconds(expectedMessage, waitForResponseInSeconds,
                () -> executeSqlMessageMovements(clientId)
                        .getValues("SUBJECT")
                        .get(0)
                        .toString());
    }
}
