package ru.yandex.autotests.directapi.finance.createinvoice;

import java.math.RoundingMode;

import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.direct.utils.money.MoneyFormat;
import ru.yandex.autotests.directapi.ApiStories;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.AxisError;
import ru.yandex.autotests.directapi.apiclient.errors.AxisErrorDetails;
import ru.yandex.autotests.directapi.common.api45.APIPort_PortType;
import ru.yandex.autotests.directapi.darkside.datacontainers.http.response.json.ClientsCreateResponse;
import ru.yandex.autotests.directapi.darkside.steps.DarkSideSteps;
import ru.yandex.autotests.directapi.finance.FinanceFeatures;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.api5.agencyclients.AddRequestMap;
import ru.yandex.autotests.directapi.model.finances.PayCampElementMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

/**
 * Author pavryabov
 * Date 14.05.14
 */
@Aqua.Test
@Features(FinanceFeatures.CREATE_INVOICE)
@Stories(ApiStories.CURRENCY)
public class CreateInvoiceSumFieldTest {

    protected LogSteps log = LogSteps.getLogger(this.getClass());

    @ClassRule
    public static ApiSteps api = new ApiSteps();

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();

    @Rule
    public Trashman trasher = new Trashman(api);

    private static DarkSideSteps darkSideSteps = api.userSteps.getDarkSideSteps();

    private static String manager = Logins.MANAGER_GEO;
    private static String rubClient = Logins.LOGIN_FOR_RUB;
    private static String usdClient = Logins.LOGIN_FOR_USD;

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6237")
    public void rubClientCreateInvoiceWithSumLessThanMinRUBCurrency() {
        api.as(rubClient).wsdl(APIPort_PortType.class);
        long campaignID = api.userSteps.addActiveCampaign(rubClient, 1);
        float sum = MoneyCurrency.get(Currency.RUB).getMinInvoiceAmount().addVAT()
                .setScale(RoundingMode.HALF_UP).getPrevious().floatValue();
        log.info("Вызываем метод CreateInvoice для кампании рублевого клиента со значением Sum меньше минимально " +
                "допустимого для данной валюты");
        api.userSteps.financeSteps().shouldGetErrorOnCreateInvoice(
                new AxisError(354, AxisErrorDetails.LOW_CURRENCY_PAYMENT_AMOUNT,
                        MoneyCurrency.get(Currency.RUB).getMinInvoiceAmount()
                                .stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                        MoneyCurrency.get(Currency.RUB).getApiDescription(), campaignID),
                new PayCampElementMap(api.type())
                        .withCampaignID(campaignID)
                        .withSum(sum)
                        .withCurrency(Currency.RUB));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6238")
    public void usdClientCreateInvoiceWithSumLessThanMinUSDCurrency() {
        api.as(usdClient).wsdl(APIPort_PortType.class);
        long campaignID = api.userSteps.addActiveCampaign(usdClient, 1);
        float sum = MoneyCurrency.get(Currency.USD).getMinInvoiceAmount().addVAT()
                .setScale(RoundingMode.HALF_UP).getPrevious().floatValue();
        log.info("Вызываем метод CreateInvoice для кампании долларового клиента со значением Sum меньше минимально " +
                "допустимого для данной валюты");
        api.userSteps.financeSteps().shouldGetErrorOnCreateInvoice(
                new AxisError(354, AxisErrorDetails.LOW_CURRENCY_PAYMENT_AMOUNT,
                        MoneyCurrency.get(Currency.USD).getMinInvoiceAmount().stringValue(MoneyFormat.TWO_DIGITS_POINT),
                        MoneyCurrency.get(Currency.USD).getApiDescription(), campaignID),
                new PayCampElementMap(api.type())
                        .withCampaignID(campaignID)
                        .withSum(sum)
                        .withCurrency(Currency.USD));
    }

    // Минимальный платеж, выполняемый менеджером
    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6239")
    public void managerCreateInvoiceWithSumLessThanServicedRUBCurrencyFirstCall() {
        //https://jira.yandex-team.ru/browse/DIRECT-24018
        String login = AddRequestMap.generateLogin("rubSubclient");
        ClientsCreateResponse createClientResponse = darkSideSteps.getClientsSteps()
                .createManagerClient(login, manager, Currency.RUB);
        api.userSteps.clientSteps().setIdmPrimaryManagerForClient(login, manager);

        long campaignID = api.as(manager).userSteps.addActiveCampaign(createClientResponse.getLogin(), 1);
        float sum = MoneyCurrency.get(Currency.RUB).getMinInvoiceAmount().addVAT()
                .setScale(RoundingMode.HALF_UP).floatValue();
        log.info("Вызываем метод CreateInvoice для рублевого клиента под менеджером. " +
                "Проверяем, что нет ограничения напервый сервисируемый платеж");
        api.userSteps.financeSteps().createInvoice(new PayCampElementMap(api.type())
                .withCampaignID(campaignID)
                .withSum(sum)
                .withCurrency(Currency.RUB));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6240")
    public void managerCreateInvoiceWithSumLessThanServicedMinUSDCurrencyFirstCall() {
        //https://jira.yandex-team.ru/browse/DIRECT-24018
        String login = AddRequestMap.generateLogin("usdSubclient");
        ClientsCreateResponse createClientResponse = darkSideSteps.getClientsSteps()
                .createManagerClient(login, manager, Currency.USD);
        api.userSteps.clientSteps().setIdmPrimaryManagerForClient(login, manager);

        long campaignID = api.as(manager).userSteps.addActiveCampaign(createClientResponse.getLogin(), 1);
        float sum = MoneyCurrency.get(Currency.USD).getMinInvoiceAmount().addVAT(Currency.RUB)
                .setScale(RoundingMode.HALF_UP).floatValue();
        log.info("Вызываем метод CreateInvoice для долларового клиента под менеджером. " +
                "Проверяем, что нет ограничения напервый сервисируемый платеж");
        api.userSteps.financeSteps().createInvoice(new PayCampElementMap(api.type())
                .withCampaignID(campaignID)
                .withSum(sum)
                .withCurrency(Currency.USD));
    }
}
