package cz.moneta.test.regression.transactional.payments.cashless.payment_engine.foreign.outgoing;

import cz.moneta.test.dsl.Harness;
import cz.moneta.test.dsl.payment_engine.enums.ForeignChannelIdentities;
import cz.moneta.test.dsl.payment_engine.enums.ForeignPaymentType;
import cz.moneta.test.dsl.payment_engine.enums.TransactionReasonPAE;
import cz.moneta.test.dsl.payment_engine.home.PaymentEngineHomePage;
import cz.moneta.test.dsl.payment_engine.tasks.PaymentEngineTasks;
import cz.moneta.test.dsl.payment_engine.utils.PaymentEngineUtils;
import cz.moneta.test.dsl.util.DateUtils;
import cz.moneta.test.dsl.util.credentials.Keys;
import cz.moneta.test.dsl.util.data.payment.PaymentData;
import cz.moneta.test.harness.annotations.Environment;
import cz.moneta.test.harness.annotations.JiraTestCase;
import cz.moneta.test.harness.annotations.TestCase;
import cz.moneta.test.harness.annotations.TestScenarioWithOrder;
import cz.moneta.test.harness.support.auth.Credentials;
import cz.moneta.test.harness.support.auth.Key;
import org.apache.commons.lang.StringUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;

import java.util.concurrent.ThreadLocalRandom;

import static cz.moneta.test.dsl.payment_engine.enums.ForeignChannelIdentities.PAE;
import static cz.moneta.test.dsl.payment_engine.enums.ForeignPaymentType.SEPA_CREDIT_TRANSFER;
import static cz.moneta.test.dsl.payment_engine.enums.TransactionReasonPAE.*;
import static cz.moneta.test.dsl.payment_engine.parts_of_menu.menu_search.PaymentEngineSearchPage.EQUIVALENT_AMOUNT_KEY;

@TestScenarioWithOrder(name = "Create foreign payment in PAE and verify.")
public class OutgoingSepaTest {
    private String transactionId;
    private PaymentData data;
    private PaymentEngineTasks tasks;
    private String TOKEN_CBL;

    @BeforeAll
    void testSetUp(Harness harness) {
        data = PaymentData.builder()
                .debtorIban(harness.getConfig("payments_cashless.foreignPayment.SEPA"))
                .debtorAcc(harness.getConfig("payments_cashless.foreignPayment.XCTacc"))
                .creditorIban("IT95G0503411401000000102077")
                .amount(ThreadLocalRandom.current().nextInt(1, 10) + "," + ThreadLocalRandom.current().nextInt(1, 99))
                .distributionGroup("SIPS")
                .payScheme("SEPA Credit Transfer")
                .instruction("OUR CLIENT REQUESTED TO CONFIRM DATE OF VALUE FOR THIS PAYMENT")
                .todayDate(DateUtils.convertRawDateForWso2(DateUtils.getTodayRawDate()))
                .creditorName("FIT \"FIT\"")
                .creditorAdressLine1("FIT Okruzni .FIT. ")
                .creditorAdressLine2("Bratislava .FIT.")
                .e2eRefDb("FIT  \"FIT\"")
                .message("FIT 3rd flook \"FIT\"")
                .channelId("IB")
                .currencyCode("23")
                .feeType("SHA")
                .build();
        TOKEN_CBL = harness.tasks().wso2().authorization().getToken("DigitalchannelsSB_CBL");
    }

    @BeforeEach
    void testSetUpUniqueData(Harness harness) {
        tasks = harness.tasks().paymentEngineTasks();
    }

    private void createForeignTransaction(Harness harness) {
        String request = harness.tasks()
                .wso2()
                .payments()
                .createRequestForForeignTransactionCreating(data);
        harness.tasks()
                .wso2()
                .payments()
                .createForeignTransaction(TOKEN_CBL, request);
    }

    private void checkTransactionStatusBooked(Harness harness, String account, String amountICBS, String transactionId) {
        String request = harness.tasks()
                .wso2()
                .payments()
                .createRequestForTransactionCheck(account, data.getTodayDate(), amountICBS);
        harness.tasks()
                .wso2()
                .payments()
                .checkTransactionStatusBooked(TOKEN_CBL, request, transactionId);
    }

    private void createForeignSepa(Harness harness, Credentials user1, ForeignPaymentType paymentType,
                                   ForeignChannelIdentities channelIdentities) {
        logInPae(harness, user1)
                .clickTransactionAndChooseCreateSctFromCreateManualMenu()
                .clickOnPaymentScheme()
                .selectPaymentScheme(paymentType)
                .clickOnChannelIdentity()
                .selectChannelIdentity(channelIdentities)
                .fillManualData(data.getAmount(), data.getDebtorIban(), data.getCreditorIban(), data.getMessageMin1())
                .clickOnExecutionDateCalendar()
                .chooseTodayExecution()
                .clickSubmit()
                .storeTransactionId()
                .clickNo();
        harness.withPaymentEngine().closePaymentEngine();
        transactionId = StringUtils.substringBetween(harness.get("TRANSACTION_ID_KEY"), "ID ", ".");
    }

    private void verifyForeignSepa(Harness harness, Credentials user2,
                                   TransactionReasonPAE status1, TransactionReasonPAE status2) {
        logInPae(harness, user2)
                .then(tasks.verifyAndWaitForStatus(transactionId, status1))
                .closeTab()
                .then(tasks.sendAndRunSCTDistribution(data))
                .then(tasks.searchTransactionAndWaitForStatus(status2, transactionId));
        harness.withPaymentEngine().closePaymentEngine();
    }

    @JiraTestCase(id = "PAY-T1752")
    @Order(1)
    @TestCase(name = "Create foreign payment", environments = {Environment.TST1, Environment.PPE})
    void createForeignPaymentSepa(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) {
        createForeignSepa(harness, user1, SEPA_CREDIT_TRANSFER, PAE);

        harness.store("reports.tmfj.execution.comment", "Transaction " + transactionId + " was successfully created."
                + "\n" + "Debtor IBAN: " + data.getDebtorIban()
                + "\n" + "Creditor IBAN: " + data.getCreditorIban()
                + "\n" + "Amount: " + data.getAmount());
    }

    @JiraTestCase(id = "PAY-T1753")
    @Order(2)
    @TestCase(name = "Verify foreign payment", environments = {Environment.TST1, Environment.PPE})
    void verifyForeignPaymentSepa(Harness harness, @Key(Keys.paymentEngine.secondUser) Credentials user2) {

        verifyForeignSepa(harness, user2, DISTRIBUTION, ARCHIV);

        harness.store("reports.tmfj.execution.comment", "Transaction " + transactionId + " was successfully archived."
                + "\n" + "Debtor IBAN: " + data.getDebtorIban()
                + "\n" + "Creditor IBAN: " + data.getCreditorIban()
                + "\n" + "Amount: " + data.getAmount());
    }

    @JiraTestCase(id = "PAY-T3631")
    @Order(3)
    @TestCase(name = "Foreign SCT Outgoing Payment Status Inquiry", environments = {Environment.TST1, Environment.PPE})
    void requestForeignSCTOutgoingPaymentStatusInquiry(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1,
                                                       @Key(Keys.paymentEngine.secondUser) Credentials user2) {
        String transactionIdSepa = transactionId;

        logInPae(harness, user1)
                .then(tasks.createRequestForSCTOutgoingPaymentStatusInquiry(transactionIdSepa, data));
        harness.withPaymentEngine().closePaymentEngine();

        transactionId = PaymentEngineUtils.getTransactionalId(harness);

        verifyForeignSepa(harness, user2, DISTRIBUTION, SENT_WAIT);

        harness.store("reports.tmfj.execution.comment", "Transaction " + transactionIdSepa + " was successfully archived."
                + "\n" + "SCT request " + transactionId + " was successfully sent, waiting for a reply (ISD)."
                + "\n" + "Debtor IBAN: " + data.getDebtorIban()
                + "\n" + "Creditor IBAN: " + data.getCreditorIban()
                + "\n" + "Amount: " + data.getAmount());
    }

    @JiraTestCase(id = "PAY-T3769")
    @Order(4)
    @TestCase(name = "Create Foreign SCT Outgoing - Automatic False Positive", environments = {Environment.TST1, Environment.PPE})
    void createForeignSCTOutgoingAutomaticFalsePositive(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1,
                                                        @Key(Keys.paymentEngine.secondUser) Credentials user2) {

        data.setDebtorIban("CZ5606000000000115115115");
        createForeignSepa(harness, user1, SEPA_CREDIT_TRANSFER, PAE);

        verifyForeignSepa(harness, user2, DISTRIBUTION, ARCHIV);

        harness.store("reports.tmfj.execution.comment", "Transaction " + transactionId + " was successfully archived."
                + "\n" + "Debtor IBAN: " + data.getDebtorIban()
                + "\n" + "Creditor IBAN: " + data.getCreditorIban()
                + "\n" + "Amount: " + data.getAmount());
    }

    @JiraTestCase(id = "PAY-T3770")
    @Order(5)
    @TestCase(name = "Create Foreign SCT Outgoing From IB to Pae - FIT", environments = {Environment.TST1, Environment.PPE})
    void createForeignSCTOutgoingFromIBtoPaeFIT(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1,
                                                @Key(Keys.paymentEngine.secondUser) Credentials user2) {

        data.setDebtorIban(harness.getConfig("payments_cashless.foreignPayment.SEPA"));
        data.setCreditorIban("SK1509000000000054174233");
        data.setAmount(ThreadLocalRandom.current().nextInt(1, 10) + "." + ThreadLocalRandom.current().nextInt(1, 99));

        createForeignTransaction(harness);

        transactionId = harness.get("TRANSACTION_ID_KEY");

        logInPae(harness, user1)
                .then(tasks.searchTransactionAndWaitForStatus(DISTRIBUTION, transactionId))
                .closeTab()
                .then(tasks.sendAndRunSCTDistribution(data))
                .then(tasks.searchTransactionAndWaitForStatus(ARCHIV, transactionId))
                .storeEquivalentAmountEur();
        harness.withPaymentEngine().closePaymentEngine();

        data.setEquivalentAmount(harness.get(EQUIVALENT_AMOUNT_KEY).toString().replace(",", "."));
        checkTransactionStatusBooked(harness, data.getDebtorAcc(), data.getEquivalentAmount(), transactionId);

        PaymentEngineUtils.logResultWithEquivalentAmount(harness, transactionId, data.getDebtorIban(),
                data.getCreditorIban(), data.getAmount() + " EUR", data.getEquivalentAmount() + " CZK");

    }

    PaymentEngineHomePage logInPae(Harness harness, Credentials credentials) {
        return harness.withPaymentEngine()
                .openLoginPage()
                .login(credentials.getUsername(), credentials.getPassword())
                .clickOkButton();
    }
}
