package cz.moneta.test.regression.transactional.payments.cashless.payment_engine.domestic.analytical;

import cz.moneta.test.dsl.Harness;
import cz.moneta.test.dsl.payment_engine.enums.TransactionReasonPAE;
import cz.moneta.test.dsl.payment_engine.model.FileForInputPreparation;
import cz.moneta.test.dsl.payment_engine.tasks.PaymentEngineTasks;
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.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Disabled;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;

import static cz.moneta.test.dsl.payment_engine.enums.TransactionReasonPAE.*;
import static cz.moneta.test.dsl.payment_engine.parts_of_menu.menu_monitoring.PaymentEngineMonitoringInstanceFileRecords.TRANSACTION_ID_KEY;
import static cz.moneta.test.dsl.payment_engine.parts_of_menu.menu_search.PaymentEngineSearchPageLifeCycle.TRANSACTION_BY_TYPE_ID_KEY;
import static cz.moneta.test.dsl.payment_engine.parts_of_menu.menu_search.PaymentEngineSearchTransactionFiles.TRANSACTION_FILE_NAME_KEY;

@TestScenarioWithOrder(name = "Simulate Starbuild Payments")
public class StarbuildTests extends FileForInputPreparation {
    private String TOKEN_CBL;
    private String HD11_FILE;
    private String HD32_FILE;
    private PaymentData data;
    private PaymentEngineTasks tasks;
    private String transactionId;

    @BeforeAll
    void setUpTestData(Harness harness) {
        data = PaymentData.builder()
                .bankName("MONETA Money Bank, a.s.")
                .nextDayDist("Ne")
                .payScheme("CZ CT Non-priority")
                .build();
        HD11_FILE = harness.getConfig("payments_cashless.foreignPayment.HD11_Starbuild");
        HD32_FILE = harness.getConfig("payments_cashless.foreignPayment.HD32_Starbuild");
        TOKEN_CBL = harness.tasks().wso2().authorization().getToken("DigitalchannelsSB_CBL");
    }

    @BeforeEach
    void setUpUniqueTestData(Harness harness) {
        tasks = new PaymentEngineTasks(harness);
        data.setAmountIcbs(ThreadLocalRandom.current().nextInt(10, 99) + "." + ThreadLocalRandom.current().nextInt(10, 99));
        data.setAmount(data.getAmountIcbs().replace(".", ""));
        data.setRandom(String.valueOf(ThreadLocalRandom.current().nextInt(1000000, 2999999)));
        data.setMessageId("YWP" + ThreadLocalRandom.current().nextInt(100000000, 999999999));
    }

    private void simulateIngoingFromStarBuildAndVerify(Harness harness, Credentials user1, Credentials user2,
                                                       String fileName, File file, TransactionReasonPAE status) {
        tasks.loginTasks().logInPae(harness, user1)
                .then(tasks.inputTrxFromStarBuild(file.getAbsolutePath()));
        harness.withPaymentEngine().closePaymentEngine();

        tasks.loginTasks().logInPae(harness, user2)
                .then(tasks.verifyAndWaitForStatusOfInputFromStarBuild(fileName, status));
        harness.withPaymentEngine().closePaymentEngine();

        transactionId = harness.get(TRANSACTION_ID_KEY);
    }

    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-T3589")
    @TestCase(name = "Simulate Outgoing HD:11 From StarBuild To ICBS - Max Data", environments = {Environment.TST1, Environment.PPE})
    void simulateOutgoingHD11FromStarBuildToIcbsMaxData(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1,
                                                  @Key(Keys.paymentEngine.secondUser) Credentials user2) throws IOException {
        data.setDebtorAcc("374299");
        data.setCreditorAcc(harness.getConfig("payments_cashless.domesticPayment.creditorAccInh"));
        data.setBankCode("0600");
        data.setHdType("11");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyMMdd"));

        String HD11FileName = "W" + data.getTodayDate() + ".00" + ThreadLocalRandom.current().nextInt(100, 999);
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));
        File HD11File = prepareFileForInput(harness, HD11_FILE, HD11FileName, data);

        try {
            simulateIngoingFromStarBuildAndVerify(harness, user1, user2, HD11FileName, HD11File, ARCHIV);

            String transactionIdIcbs = data.getTodayDate() + data.getMessageId();
            data.setTodayDate(DateUtils.getFormattedTodayDate("yyyy-MM-dd"));

            checkTransactionStatusBooked(harness, data.getCreditorAcc(), data.getAmountIcbs(), transactionIdIcbs);

            harness.store("reports.tmfj.execution.comment", "Transaction " + transactionId + " was successfully archived and booked in ICBS."
                    + "\n" + "StarBuild file name: " + HD11FileName
                    + "\n" + "Debtor account: " + data.getDebtorAcc() + "/" + data.getBankCode()
                    + "\n" + "Creditor account: " + data.getCreditorAcc()
                    + "\n" + "Amount: " + data.getAmountIcbs() + " CZK");

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

    @Order(2)
  	@Disabled("Disabled on request from Martin Sudek")
    @JiraTestCase(id = "PAY-T3590")
    @TestCase(name = "Simulate Outgoing HD:11 From StarBuild - Max Data", environments = {Environment.TST1, Environment.PPE})
    void simulateOutgoingHD11FromStarBuildMaxData(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1,
                                                  @Key(Keys.paymentEngine.secondUser) Credentials user2) throws IOException {
        data.setDebtorAcc("374299");
        data.setCreditorAcc(harness.getConfig("payments_cashless.domesticPayment.creditorAccInh"));
        data.setBankCode("0100");
        data.setHdType("11");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyMMdd"));
        data.setChannelName("O_CCO_CERTIS");

        String HD11FileName = "W" + data.getTodayDate() + ".00" + ThreadLocalRandom.current().nextInt(100, 999);
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));
        File HD11File = prepareFileForInput(harness, HD11_FILE, HD11FileName, data);

        try {
            simulateIngoingFromStarBuildAndVerify(harness, user1, user2, HD11FileName, HD11File, DISTRIBUTION);

            tasks.loginTasks().logInPae(harness, user1)
                    .then(tasks.sendAndRunCZCTDDistribution(data, ARCHIV, harness.get(TRANSACTION_ID_KEY)))
                    .then(tasks.checkTransactionChannelAndStoreFileName(data));
            harness.withPaymentEngine().closePaymentEngine();

            harness.store("reports.tmfj.execution.comment", "Transaction " + transactionId + " was successfully archived."
                    + "\n" + "StarBuild file name: " + HD11FileName
                    + "\n" + "CERTIS file name: " + harness.get(TRANSACTION_FILE_NAME_KEY)
                    + "\n" + "Debtor account: " + data.getDebtorAcc() + "/" + data.getBankCode()
                    + "\n" + "Creditor account: " + data.getCreditorAcc()
                    + "\n" + "Amount: " + data.getAmountIcbs() + " CZK");

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

    @Order(3)
  	@Disabled("Disabled on request from Martin Sudek")
    @JiraTestCase(id = "PAY-T3591")
    @TestCase(name = "Simulate Outgoing HD:32 From StarBuild to ICBS - Max Data", environments = {Environment.TST1, Environment.PPE})
    void simulateOutgoingHD32FromStarBuildToIcbsMaxData(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1,
                                                        @Key(Keys.paymentEngine.secondUser) Credentials user2) throws IOException {
        data.setDebtorAcc(harness.getConfig("payments_cashless.domesticPayment.debtorAcc"));
        data.setCreditorAcc("90870957");
        data.setBankCode("0600");
        data.setHdType("32");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyMMdd"));
        data.setChannelName("O_CCI_SB_HD");
        data.setTransactionType("HD:55 (HD:32) prichozi");

        String HD32FileName = "W" + data.getTodayDate() + "." + ThreadLocalRandom.current().nextInt(100, 999);
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));
        File HD32File = prepareFileForInput(harness, HD32_FILE, HD32FileName, data);
        try {
            simulateIngoingFromStarBuildAndVerify(harness, user1, user2, HD32FileName, HD32File, ARCHIV);

            tasks.loginTasks().logInPae(harness, user2)
                    .then(tasks.searchTransactionAndWaitForStatus(ARCHIV, transactionId))
                    .clickLifeCycle()
                    .waitForStatus(harness, INGOING_WAIT)
                    .storeTransactionIdByType(data.getTransactionType())
                    .closeTab()
                    .then(tasks.sendAndRunStarBuildDistribution())
                    .then(tasks.searchTransactionAndWaitForStatus(REDIRECT_TO_STARBUILD, harness.get(TRANSACTION_BY_TYPE_ID_KEY)))
                    .waitForStatus(harness, INGOING_ARCHIV)
                    .then(tasks.checkTransactionChannelAndStoreFileName(data));
            harness.withPaymentEngine().closePaymentEngine();

            harness.store("reports.tmfj.execution.comment", "HD:32 transaction " + transactionId + " was successfully archived."
                    + "\n" + "HD:55 transaction " + harness.get(TRANSACTION_BY_TYPE_ID_KEY) + " was successfully redirected to StarBuild."
                    + "\n" + "StarBuild file name: " + HD32FileName
                    + "\n" + "CERTIS file name: " + harness.get(TRANSACTION_FILE_NAME_KEY)
                    + "\n" + "Debtor account: " + data.getDebtorAcc() + "/" + data.getBankCode()
                    + "\n" + "Creditor account: " + data.getCreditorAcc()
                    + "\n" + "Amount: " + data.getAmountIcbs() + " CZK");

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

    @Order(4)
  	@Disabled("Disabled on request from Martin Sudek")
    @JiraTestCase(id = "PAY-T3592")
    @TestCase(name = "Simulate Outgoing HD:32 From StarBuild - Max Data", environments = {Environment.TST1, Environment.PPE})
    void simulateOutgoingHD32FromStarBuildMaxData(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1,
                                                        @Key(Keys.paymentEngine.secondUser) Credentials user2) throws IOException {
        data.setDebtorAcc("123");
        data.setCreditorAcc("90870957");
        data.setBankCode("0300");
        data.setHdType("32");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyMMdd"));
        data.setChannelName("O_CCO_CERTIS");
        data.setTransactionType("HD:32 odchozi");

        String HD32FileName = "W" + data.getTodayDate() + "." + ThreadLocalRandom.current().nextInt(100, 999);
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));
        File HD32File = prepareFileForInput(harness, HD32_FILE, HD32FileName, data);
        try {
            simulateIngoingFromStarBuildAndVerify(harness, user1, user2, HD32FileName, HD32File, DISTRIBUTION);

            tasks.loginTasks().logInPae(harness, user2)
                    .then(tasks.sendAndRunCZCTDDistribution(data, ARCHIV, transactionId))
                    .then(tasks.checkTransactionChannelAndStoreFileName(data));
            harness.withPaymentEngine().closePaymentEngine();

            harness.store("reports.tmfj.execution.comment", "HD:32 transaction " + transactionId + " was successfully archived."
                    + "\n" + "StarBuild file name: " + HD32FileName
                    + "\n" + "CERTIS file name: " + harness.get(TRANSACTION_FILE_NAME_KEY)
                    + "\n" + "Debtor account: " + data.getDebtorAcc() + "/" + data.getBankCode()
                    + "\n" + "Creditor account: " + data.getCreditorAcc()
                    + "\n" + "Amount: " + data.getAmountIcbs() + " CZK");

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