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

import cz.moneta.test.dsl.Harness;
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 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.SECOND_ROW_AMOUNT_KEY;
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.PaymentEngineSearchTransactionDetailLifeCycle.*;

@TestScenarioWithOrder(name = "Simulate Ingoing From Certis")
public class IngoingCertisTest extends FileForInputPreparation {
    private String TOKEN_CBL;
    private String HD01_FILE;
    private String HD11_14_FILE;
    private String HD32FILE;
    private PaymentData data;
    private PaymentEngineTasks tasks;

    @BeforeAll
    void setUpTestData(Harness harness) {
        data = PaymentData.builder()
                .debtorAcc(harness.getConfig("payments_cashless.domesticPayment.debtorAcc"))
                .creditorAcc(harness.getConfig("payments_cashless.domesticPayment.creditorAccInh"))
                .bankName("MONETA Money Bank, a.s.")
                .nextDayDist("Ne")
                .payScheme("CZ CT Non-priority")
                .build();
        HD01_FILE = harness.getConfig("payments_cashless.foreignPayment.HD01_FILE");
        HD11_14_FILE = harness.getConfig("payments_cashless.foreignPayment.HD11-14_FILE");
        HD32FILE = harness.getConfig("payments_cashless.foreignPayment.HD32_FILE");
        TOKEN_CBL = harness.tasks().wso2().authorization().getToken("DigitalchannelsSB_CBL");
    }

    @BeforeEach
    void setUpUniqueTestData(Harness harness) {
        tasks = new PaymentEngineTasks(harness);
        data.setAmount(String.valueOf(ThreadLocalRandom.current().nextInt(1, 299)));
        data.setRandom(String.valueOf(ThreadLocalRandom.current().nextInt(1000000, 2999999)));
        data.setMessageId(String.valueOf(ThreadLocalRandom.current().nextInt(100000, 999999)));
        data.setLastNonpriorityField(ThreadLocalRandom.current().nextInt(501, 698));
        data.setLastPriorityField(ThreadLocalRandom.current().nextInt(701, 898));
    }

    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-T3585")
    @TestCase(name = "Simulate Ingoing HD:01 From Certis - Max Data", environments = {Environment.TST1, Environment.PPE})
    void simulateIngoingHD01FromCertisMaxData(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {
        data.setHdType("01");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));

        String HD01FileName = data.getTodayDate() + "_0600_000" + data.getLastPriorityField() + "_IH";
        File HD01File = prepareFileForInput(harness, HD01_FILE, HD01FileName, data);

        simulateIngoingFromCertis(harness, user1, HD01FileName, HD01File);
    }

    @Order(2)
    @JiraTestCase(id = "PAY-T3602")
    @TestCase(name = "Simulate Ingoing HD:12 From Certis - Max Data", environments = {Environment.TST1, Environment.PPE})
    void simulateIngoingHD12FromCertisMaxData(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {
        data.setHdType("12");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));

        String HD11_14FileName = data.getTodayDate() + "_0600_000" + data.getLastNonpriorityField() + "_IL";
        File HD11_14File = prepareFileForInput(harness, HD11_14_FILE, HD11_14FileName, data);

        simulateIngoingFromCertis(harness, user1, HD11_14FileName, HD11_14File);
    }

    @Order(3)
    @JiraTestCase(id = "PAY-T3603")
    @TestCase(name = "Simulate Ingoing HD:13 From Certis - Max Data", environments = {Environment.TST1, Environment.PPE})
    void simulateIngoingHD13FromCertisMaxData(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {
        data.setHdType("13");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));

        String HD11_14FileName = data.getTodayDate() + "_0600_000" + data.getLastNonpriorityField() + "_IL";
        File HD11_14File = prepareFileForInput(harness, HD11_14_FILE, HD11_14FileName, data);

        simulateIngoingFromCertis(harness, user1, HD11_14FileName, HD11_14File);
    }

    @Order(4)
    @JiraTestCase(id = "PAY-T3604")
    @TestCase(name = "Simulate Ingoing HD:14 From Certis - Max Data", environments = {Environment.TST1, Environment.PPE})
    void simulateIngoingHD14FromCertisMaxData(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {
        data.setHdType("14");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));

        String HD11_14FileName = data.getTodayDate() + "_0600_000" + data.getLastNonpriorityField() + "_IL";
        File HD11_14File = prepareFileForInput(harness, HD11_14_FILE, HD11_14FileName, data);

        simulateIngoingFromCertis(harness, user1, HD11_14FileName, HD11_14File);
    }

    @Order(5)
    @JiraTestCase(id = "PAY-T3587")
    @TestCase(name = "Simulate Ingoing HD:32 From Certis With HD:12 - valid authorization for direct debit", environments = {Environment.TST1, Environment.PPE})
    void simulateIngoingHD32FromCertisWithHD12(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {
        data.setDebtorAcc(harness.getConfig("payments_cashless.domesticPayment.creditorAccInh"));
        data.setHdType("32");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));
        data.setTransactionType("HD:12 odchozi");

        String HD32FileName = data.getTodayDate() + "_0600_000" + data.getLastNonpriorityField() + "_IL";
        File HD32File = prepareFileForInput(harness, HD32FILE, HD32FileName, data);

        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyy-MM-dd"));

        try {
            tasks.loginTasks().logInPae(harness, user1)
                    .then(tasks.inputCCIFromCERTIS(HD32File.getAbsolutePath()))
                    .then(tasks.checkStatusOfCCIFromCERTIS(HD32FileName, ARCHIV))
                    .then(tasks.searchTransactionAndWaitForStatus(ARCHIV, harness.get(TRANSACTION_ID_KEY)))
                    .then(tasks.checkLifeCycleAndWaitForStatus(data, RELEASE))
                    .storeTransactionIdByType(data.getTransactionType())
                    .closeTab()
                    .then(tasks.runReleaseAfterDispoCheck(DISTRIBUTION, harness.get(TRANSACTION_BY_TYPE_ID_KEY)))
                    .closeTab()
                    .then(tasks.sendAndRunCZCTDDistribution(data, ARCHIV, harness.get(TRANSACTION_BY_TYPE_ID_KEY)));
            harness.withPaymentEngine().closePaymentEngine();

            String transactionId = harness.get(TRANSACTION_ID_KEY);
            String transactionIdFromFile = DateUtils.getFormattedTodayDate("yyMMdd") + "IDHD" + data.getHdType() + "x" + data.getMessageId();
            data.setAmount(harness.get(SECOND_ROW_AMOUNT_KEY).toString().replace(",", "."));

            checkTransactionStatusBooked(harness, data.getCreditorAcc(), data.getAmount(), transactionIdFromFile);

            harness.store("reports.tmfj.execution.comment", "HD:32 " + transactionId + " was successfully archived."
                    + "\n" + "Originators Document ID " + transactionIdFromFile + " was successfully archived in ICBS."
                    + "\n" + "HD:12 " + harness.get(TRANSACTION_BY_TYPE_ID_KEY) + " was successfully archived. "
                    + "\n" + "File name: " + HD32FileName
                    + "\n" + "Debtor account: " + data.getDebtorAcc()
                    + "\n" + "Creditor account: " + data.getCreditorAcc()
                    + "\n" + "Amount: " + data.getAmount());

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

    @Order(6)
    @JiraTestCase(id = "PAY-T3593")
    @TestCase(name = "Simulate Ingoing HD:32 From Certis With HD:55", environments = {Environment.TST1, Environment.PPE})
    void simulateIngoingHD32FromCertisWithHD55(Harness harness, @Key(Keys.paymentEngine.firstUser) Credentials user1) throws IOException {
        data.setDebtorAcc(harness.getConfig("payments_cashless.domesticPayment.accountCZK"));
        data.setHdType("32");
        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyyMMdd"));
        data.setTransactionType("HD:55 (HD:32) odchozi");

        String HD32FileName = data.getTodayDate() + "_0600_000" + data.getLastNonpriorityField() + "_IL";
        File HD32File = prepareFileForInput(harness, HD32FILE, HD32FileName, data);

        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyy-MM-dd"));

        try {
            tasks.loginTasks().logInPae(harness, user1)
                    .then(tasks.inputCCIFromCERTIS(HD32File.getAbsolutePath()))
                    .then(tasks.checkStatusOfCCIFromCERTIS(HD32FileName, ARCHIV))
                    .then(tasks.searchTransactionAndWaitForStatus(ARCHIV, harness.get(TRANSACTION_ID_KEY)))
                    .then(tasks.checkLifeCycleAndWaitForStatus(data, DISTRIBUTION))
                    .storeTransactionIdByType(data.getTransactionType())
                    .closeTab()
                    .then(tasks.sendAndRunCZCTDDistribution(data, ARCHIV, harness.get(TRANSACTION_BY_TYPE_ID_KEY)));
            harness.withPaymentEngine().closePaymentEngine();

            harness.store("reports.tmfj.execution.comment", "HD:32 " + harness.get(TRANSACTION_ID_KEY) + " was successfully archived."
                    + "\n" + "HD:55 " + harness.get(TRANSACTION_BY_TYPE_ID_KEY) + " was successfully archived."
                    + "\n" + "File name: " + HD32FileName
                    + "\n" + "Debtor account: " + data.getDebtorAcc()
                    + "\n" + "Creditor account: " + data.getCreditorAcc()
                    + "\n" + "Amount: " + harness.get(SECOND_ROW_AMOUNT_KEY));

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

    private void simulateIngoingFromCertis(Harness harness, Credentials user1, String fileName, File file) {

        data.setTodayDate(DateUtils.getFormattedTodayDate("yyyy-MM-dd"));

        try {
            tasks.loginTasks().logInPae(harness, user1)
                    .then(tasks.inputCCIFromCERTIS(file.getAbsolutePath()))
                    .then(tasks.checkStatusOfCCIFromCERTIS(fileName, RELEASE))
                    .then(tasks.runReleaseAfterDispoCheck(ARCHIV, harness.get(TRANSACTION_ID_KEY)));
            harness.withPaymentEngine().closePaymentEngine();

            String transactionId = harness.get(TRANSACTION_ID_KEY);
            String transactionIdFromFile = DateUtils.getFormattedTodayDate("yyMMdd") + "IDHD" + data.getHdType() + "x" + data.getMessageId();
            data.setAmount(harness.get(SECOND_ROW_AMOUNT_KEY).toString().replace(",", "."));

            checkTransactionStatusBooked(harness, data.getCreditorAcc(), data.getAmount(), transactionIdFromFile);

            harness.store("reports.tmfj.execution.comment", "Transaction " + transactionId + " was successfully archived."
                    + "\n" + "Originators Document ID " + transactionIdFromFile + " was successfully archived in ICBS."
                    + "\n" + "File name: " + fileName
                    + "\n" + "Debtor account: " + data.getDebtorAcc()
                    + "\n" + "Creditor account: " + data.getCreditorAcc()
                    + "\n" + "Amount: " + data.getAmount());

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