package cz.moneta.test.regression.transactional.payments.cashlessFirstTests.payment_engine.foreign.ingoing;

import cz.moneta.test.dsl.Harness;
import cz.moneta.test.dsl.payment_engine.parts_of_menu.menu_monitoring.PaymentEngineMonitoringInstanceFileRecords;
import cz.moneta.test.dsl.payment_engine.parts_of_menu.menu_monitoring.PaymentEngineMonitoringInstanceLifeCycle;
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.*;
import cz.moneta.test.harness.support.auth.Credentials;
import cz.moneta.test.harness.support.auth.Key;
import cz.moneta.test.dsl.payment_engine.model.FileForInputPreparation;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Order;

import java.io.*;
import java.util.concurrent.ThreadLocalRandom;

import static cz.moneta.test.dsl.payment_engine.enums.CurrencyPAE.*;
import static cz.moneta.test.dsl.payment_engine.parts_of_menu.menu_monitoring.PaymentEngineMonitoringInstanceFileRecords.*;
import static cz.moneta.test.dsl.payment_engine.enums.TransactionReasonPAE.*;
import static cz.moneta.test.dsl.payment_engine.parts_of_menu.menu_monitoring.PaymentEngineRunInstance.LAST_SEQUENCE_NUMBER_KEY;
import static cz.moneta.test.dsl.payment_engine.parts_of_menu.menu_search.PaymentEngineSearchTransactionDetail.REF_TRANSACTION_KEY;

@TestScenarioWithOrder(name = "Foreign Payment From MC controller")
public class ForeignPaymentFromMcTest extends FileForInputPreparation {
    private String TOKEN_CBL;
    private String MC_CFA_FILE;
    private String MC_PAIN_FILE;
    private String MC_CFD_FILE;
    private String XCT_RETURN_FILE;
    private String transactionId;
    private PaymentEngineTasks tasks;
    private final String filesTabName = "Soubory";
    private PaymentData data;

    @BeforeAll
    public void testSetUp(Harness harness) {
        MC_CFA_FILE = harness.getConfig("payments_cashless.foreignPayment.cfaFile");
        MC_PAIN_FILE = harness.getConfig("payments_cashless.foreignPayment.painFile");
        MC_CFD_FILE = harness.getConfig("payments_cashless.foreignPayment.cfdFile");
        XCT_RETURN_FILE = harness.getConfig("payments_cashless.foreignPayment.xctReturnFile");
        TOKEN_CBL = harness.tasks().wso2().authorization().getToken("DigitalchannelsSB_CBL");
        data = PaymentData.builder()
                .iban(harness.getConfig("payments_cashless.foreignPayment.foreignIban"))
                .todayDate(DateUtils.convertRawDateForWso2(DateUtils.getTodayRawDate()))
                .build();
    }

    @BeforeEach
    public void testSetUpUniqueData(Harness harness) {
        tasks = harness.tasks().paymentEngineTasks();
        data.setAmount(ThreadLocalRandom.current().nextInt(1, 9) + "," + ThreadLocalRandom.current().nextInt(10, 99));
        data.setAmount1(data.getAmount().replace(",", "."));
        data.setRandom(String.valueOf(ThreadLocalRandom.current().nextInt(100000000, 999999999)));
    }

    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);
    }

    @Order(1)
    @JiraTestCase(id = "PAY-T3599")
    @TestCase(name = "Create Input CFA From MC", environments = {Environment.TST1, Environment.PPE})
    void createInputCFAFromMC(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {

        data.setDebtorAcc(harness.getConfig("payments_cashless.foreignPayment.debtorAccMcCFA"));
        String newFileName = DateUtils.getFormattedTodayDate("yyMMdd") + "11525" + data.getRandom() + "_0.CFA";
        File file = prepareFileForInput(harness, MC_CFA_FILE, newFileName, data);

        try {
            tasks.loginTasks().logInPae(harness, user1)
                    .then(tasks.inputCFAFromMC(file.getAbsolutePath()))
                    .then(tasks.checkStatusOfCFAFromMC(DISTRIBUTION, newFileName))
                    .then(tasks.sendAndRunXCTDistribution())
                    .then(tasks.checkStatusOfCFAFromMC(ARCHIV, newFileName));
            harness.withPaymentEngine().closePaymentEngine();

            transactionId = harness.get(TRANSACTION_ID_KEY);
            String equivalentAmount = harness.get(PaymentEngineMonitoringInstanceFileRecords.EQUIVALENT_AMOUNT_KEY)
                    .toString().replace(".", "").replace(",", ".");

            checkTransactionStatusBooked(harness, data.getDebtorAcc(), equivalentAmount, transactionId);

            PaymentEngineUtils.logResultOfInputWithEquivalentAmount(harness, newFileName, transactionId, data.getAmount(),
                    CURRENCY_USD_SHORT, equivalentAmount, CURRENCY_CZK_SHORT);

        } catch (Exception e) {
            throw e;
        } finally {
            file.delete();
        }
    }

    @Disabled
    @Order(2)
    @JiraTestCase(id = "PAY-T3691")
    @TestCase(name = "Create Return Input CFA From MC", environments = {Environment.TST1, Environment.PPE})
    void createReturnInputCFAFromMC(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {

        data.setDebtorAcc(harness.getConfig("payments_cashless.foreignPayment.debtorAccMcCFA"));
        data.setIban(harness.getConfig("payments_cashless.foreignPayment.ibanMcCFA"));

        tasks.loginTasks().logInPae(harness, user1)
                .then(tasks.searchTransactionAndWaitForStatus(ARCHIV, transactionId))
                .then(tasks.checkTransactionDetailAndStoreRefTransactionId());
        harness.withPaymentEngine().closePaymentEngine();
        File xctReturnFile = null;

        try {
            tasks.loginTasks().logInPae(harness, user1)
                    .then(tasks.storeLastMTId(filesTabName));
            harness.withPaymentEngine().closePaymentEngine();

            data.setTrxReference(harness.get(REF_TRANSACTION_KEY));
            lastField = Integer.valueOf(harness.get(LAST_SEQUENCE_NUMBER_KEY));
            String xctReturnFileName = String.format("0106%04d.out", lastField + 1);
            xctReturnFile = prepareFileForInput(harness, XCT_RETURN_FILE, xctReturnFileName, data);

            tasks.loginTasks().logInPae(harness, user1)
                    .then(tasks.inputMTFromSAA(xctReturnFile.getAbsolutePath()))
                    .then(tasks.checkStatusOfMTFromSAA(xctReturnFileName, ARCHIV))
                    .storeEquivalentAmountCzk();
            harness.withPaymentEngine().closePaymentEngine();

            transactionId = harness.get(TRANSACTION_ID_KEY);
            String equivalentAmount = harness.get(PaymentEngineMonitoringInstanceFileRecords.EQUIVALENT_AMOUNT_KEY)
                    .toString().replace(".", "").replace(",", ".");

            checkTransactionStatusBooked(harness, data.getDebtorAcc(), equivalentAmount, transactionId);

            PaymentEngineUtils.logResultOfInputWithEquivalentAmount(harness, xctReturnFileName, transactionId, data.getAmount(),
                    CURRENCY_USD_SHORT, equivalentAmount, CURRENCY_CZK_SHORT);

        } catch (Exception e) {
            throw e;
        } finally {
            xctReturnFile.delete();
        }
    }

    @Order(3)
    @JiraTestCase(id = "PAY-T3601")
    @TestCase(name = "Create Input PAIN From MC", environments = {Environment.TST1, Environment.PPE})
    void createInputPAINFromMC(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {

        data.setDebtorAcc(harness.getConfig("payments_cashless.foreignPayment.foreignCreditor"));
        data.setIban(harness.getConfig("payments_cashless.foreignPayment.foreignIban"));

        String newFileName = DateUtils.getFormattedTodayDate("yyMMdd") + "11032" + data.getRandom() + "_0.CCT";
        File file = prepareFileForInput(harness, MC_PAIN_FILE, newFileName, data);

        try {
            tasks.loginTasks().logInPae(harness, user1)
                    .then(tasks.inputPAINFromMC(file.getAbsolutePath()))
                    .then(tasks.checkStatusOfPAINFromMC(newFileName, DISTRIBUTION))
                    .then(tasks.sendAndRunXCTDistribution())
                    .then(tasks.checkStatusOfPAINFromMC(newFileName, ARCHIV));
            harness.withPaymentEngine().closePaymentEngine();

            transactionId = harness.get(TRANSACTION_ID_KEY);
            String equivalentAmount = harness.get(PaymentEngineMonitoringInstanceFileRecords.EQUIVALENT_AMOUNT_KEY)
                    .toString().replace(".", "").replace(",", ".");

            checkTransactionStatusBooked(harness, data.getDebtorAcc(), equivalentAmount, transactionId);

            PaymentEngineUtils.logResultOfInputWithEquivalentAmount(harness, newFileName, transactionId, data.getAmount1(),
                    CURRENCY_EUR_SHORT, equivalentAmount, CURRENCY_CZK_SHORT);

        } catch (Exception e) {
            throw e;
        } finally {
            file.delete();
        }
    }

    @Order(4)
    @JiraTestCase(id = "PAY-T3600")
    @TestCase(name = "Create Input CFD From MC", environments = {Environment.TST1, Environment.PPE})
    void createInputCFDFromMC(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {

        data.setDebtorAcc(harness.getConfig("payments_cashless.domesticPayment.debtorAcc"));
        data.setCreditorAcc(harness.getConfig("payments_cashless.foreignPayment.foreignCreditor"));
        data.setAmount(String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999)));
        data.setAmount1(String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999)));
        data.setTrxReference(String.valueOf(Integer.parseInt(data.getAmount()) + Integer.parseInt(data.getAmount1())));

        String newFileName = DateUtils.getFormattedTodayDate("yyMMdd") + "08043" + data.getRandom() + "_0.CFD";
        File file = prepareFileForInput(harness, MC_CFD_FILE, newFileName, data);

        try {
            tasks.loginTasks().logInPae(harness, user1)
                    .then(tasks.inputCFDFromMC(file.getAbsolutePath()))
                    .then(tasks.checkStatusOfCFDFromMC(newFileName, ARCHIV));
            harness.withPaymentEngine().closePaymentEngine();

            String outgoingTransactionId = harness.get(TRANSACTION_ID_KEY);
            transactionId = harness.get(OUTGOING_TRANSACTION_ID_KEY);
            String ingoingTransactionId = harness.get(PaymentEngineMonitoringInstanceLifeCycle.INGOING_HD11_TRANSACTION_ID_KEY);
            String transactionAmount = harness.get(FIRST_ROW_AMOUNT_KEY).toString().replace(",", ".");
            String outgoingTransactionAmount = harness.get(SECOND_ROW_AMOUNT_KEY).toString().replace(",", ".");

            checkTransactionStatusBooked(harness, data.getDebtorAcc(), transactionAmount, transactionId);
            checkTransactionStatusBooked(harness, data.getCreditorAcc(), outgoingTransactionAmount, outgoingTransactionId);
            checkTransactionStatusBooked(harness, data.getDebtorAcc(), outgoingTransactionAmount, outgoingTransactionId);

            PaymentEngineUtils.logResultOfInputLong(harness, newFileName, outgoingTransactionId, outgoingTransactionAmount,
                    ingoingTransactionId, transactionId, transactionAmount, CURRENCY_CZK_SHORT);

        } catch (Exception e) {
            throw e;
        } finally {
            file.delete();
        }
    }
}
