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

import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
import org.junit.BeforeClass;
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.Money;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.direct.utils.money.MoneyFormat;
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.finance.FinanceFeatures;
import ru.yandex.autotests.directapi.finance.FinanceLogins;
import ru.yandex.autotests.directapi.model.User;
import ru.yandex.autotests.directapi.model.finances.PayCampElementMap;
import ru.yandex.autotests.directapi.model.finances.PayCampaignsInfoMap;
import ru.yandex.autotests.directapi.model.finances.PayMethod;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directapi.steps.ConditionFactories;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 * Author pavryabov
 * Date 22.04.14
 */
@Aqua.Test
@Features(FinanceFeatures.PAY_CAMPAIGNS)
public class PayCampaignsOverdraftTest {
    private LogSteps log = LogSteps.getLogger(this.getClass());

    private static final String CLIENT_LOGIN = FinanceLogins.OVERDRAFT_CLIENT4;
    private static final Currency CURRENCY = Currency.RUB;

    @ClassRule
    public static ApiSteps api = new ApiSteps().version(104).as(CLIENT_LOGIN);

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

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

    private static Money sum = MoneyCurrency.get(CURRENCY).getMinInvoiceAmount();
    private static float startCampaignSum = 1100f;
    private static int overdraftLimit = 20000;
    private static float startCampaignSumWithVAT = Money.valueOf(startCampaignSum, CURRENCY).addVAT().floatValue();
    private static float sumWithVAT = Money.valueOf(sum.floatValue(), CURRENCY).addVAT().floatValue();
    protected static long activeCampaignID1;
    protected static long activeCampaignID2;
    protected static long deletedCampaignID;
    protected static long draftCampaignID;
    protected static long moderatedCampaignID;

    @BeforeClass
    public static void initTest() {
        api.userSteps.balanceSteps().setClientOverdraftByLogin(CLIENT_LOGIN, overdraftLimit, CURRENCY);
        api.userSteps.balanceSteps().verifyHasPhPerson(Integer.parseInt(User.get(CLIENT_LOGIN).getClientID()));
        activeCampaignID1 = api.userSteps.addActiveCampaign(CLIENT_LOGIN, startCampaignSumWithVAT, CURRENCY);
        activeCampaignID2 = api.userSteps.addActiveCampaign(CLIENT_LOGIN, 1);
        moderatedCampaignID = api.userSteps.addModeratedCampaign(CLIENT_LOGIN);
        draftCampaignID = api.userSteps.addDraftCampaign(CLIENT_LOGIN);
        deletedCampaignID = api.userSteps.campaignSteps().addDefaultTextCampaign(CLIENT_LOGIN);
        api.userSteps.campaignSteps().campaignsDelete(deletedCampaignID);
        api.userSteps.balanceSteps().synchronizeWithBalance(activeCampaignID1);
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6418")
    public void testPayNotMyCampaign() {
        log.info("Попытка оплатить кампанию, на которую нет прав (263) вместе с кампанией, на которую есть права");
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaigns(
                new AxisError(54, null),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                        .withCampaignID(activeCampaignID2)
                                        .withCurrency(Currency.RUB)
                                        .withSum(sum.floatValue()),
                                new PayCampElementMap(api.type())
                                        .withCampaignID(263)
                                        .withCurrency(Currency.RUB)
                                        .withSum(sum.floatValue()))
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6423")
    public void testPayDeletedCampaign() {
        log.info("Попытка оплаты несуществующей (была удалена) кампании");
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaigns(
                new AxisError(1, null),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                        .withCampaignID(deletedCampaignID)
                                        .withCurrency(Currency.RUB)
                                        .withSum(sum.floatValue()),
                                new PayCampElementMap(api.type())
                                        .withCampaignID(activeCampaignID2)
                                        .withCurrency(Currency.RUB)
                                        .withSum(sum.floatValue()))
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6421")
    public void testPayDraftCampaign() {
        log.info("Попытка оплаты неактивной кампании");
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaigns(
                new AxisError(354, AxisErrorDetails.CAMPAIGN_NOT_MODERATED, draftCampaignID),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                .withCampaignID(draftCampaignID)
                                .withCurrency(CURRENCY)
                                .withSum(sum.floatValue()))
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6422")
    public void testPayModeratedCampaign() {
        log.info("Оплата модерированной кампании");
        CampaignGetItem campaign = api.userSteps.campaignSteps().getCampaign(moderatedCampaignID);
        int response = api.userSteps.financeSteps().payCampaignsOverdraft(
                new PayCampElementMap(api.type())
                        .withCampaignID(moderatedCampaignID)
                        .withCurrency(CURRENCY)
                        .withSum(sumWithVAT));
        assertThat("Метод PayCampaigns вернул неуспешный код завершения операции", response, equalTo(1));
        ConditionFactories.NOTIFY_ORDER2.until(
                api.userSteps.campaignSteps().campaignFundsChangedOnFunds(campaign, sum));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6424")
    public void testPayModeratedAndActiveCampaign() {
        log.info("Оплата модерированной и активной кампаний");
        CampaignGetItem campaignModerated = api.userSteps.campaignSteps().getCampaign(moderatedCampaignID);
        CampaignGetItem campaignActive = api.userSteps.campaignSteps().getCampaign(activeCampaignID1);
        int response = api.userSteps.financeSteps().payCampaignsOverdraft(
                new PayCampElementMap(api.type())
                        .withCampaignID(moderatedCampaignID)
                        .withCurrency(CURRENCY)
                        .withSum(sumWithVAT),
                new PayCampElementMap(api.type())
                        .withCampaignID(activeCampaignID1)
                        .withCurrency(CURRENCY)
                        .withSum(sumWithVAT));
        assertThat("Метод PayCampaigns вернул неуспешный код завершения операции", response, equalTo(1));
        ConditionFactories.NOTIFY_ORDER2.until(
                api.userSteps.campaignSteps().campaignFundsChangedOnFunds(campaignModerated, sum));
        ConditionFactories.NOTIFY_ORDER2.until(
                api.userSteps.campaignSteps().campaignFundsChangedOnFunds(campaignActive, sum));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6425")
    public void testPayActiveCampaign() {
        log.info("Оплата активной кампании");
        CampaignGetItem campaign = api.userSteps.campaignSteps().getCampaign(activeCampaignID1);
        int response = api.userSteps.financeSteps().payCampaignsOverdraft(
                new PayCampElementMap(api.type())
                        .withCampaignID(activeCampaignID1)
                        .withCurrency(CURRENCY)
                        .withSum(sumWithVAT));
        assertThat("Метод PayCampaigns вернул неуспешный код завершения операции", response, equalTo(1));
        ConditionFactories.NOTIFY_ORDER2.until(
                api.userSteps.campaignSteps().campaignFundsChangedOnFunds(campaign, sum));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6426")
    public void testPayTwoActiveCampaigns() {
        Float multi = 1.2f; // koefficient until DIRECT-61288
        Money fixedSum = Money.valueOf(sum.floatValue() * multi, CURRENCY);
        Float fixedSumWithVAT = Money.valueOf(fixedSum.floatValue(), CURRENCY).addVAT().floatValue();
        log.info("Оплата двух активных кампаний");
        CampaignGetItem campaignActive1 = api.userSteps.campaignSteps().getCampaign(activeCampaignID1);
        CampaignGetItem campaignActive2 = api.userSteps.campaignSteps().getCampaign(activeCampaignID2);
        int response = api.userSteps.financeSteps().payCampaignsOverdraft(
                new PayCampElementMap(api.type())
                        .withCampaignID(activeCampaignID1)
                        .withCurrency(CURRENCY)
                        .withSum(fixedSumWithVAT),
                new PayCampElementMap(api.type())
                        .withCampaignID(activeCampaignID2)
                        .withCurrency(CURRENCY)
                        .withSum(fixedSumWithVAT));
        assertThat("Метод PayCampaigns вернул неуспешный код завершения операции", response, equalTo(1));
        ConditionFactories.NOTIFY_ORDER2.until(
                api.userSteps.campaignSteps().campaignFundsChangedOnFunds(campaignActive1, fixedSum));
        ConditionFactories.NOTIFY_ORDER2.until(
                api.userSteps.campaignSteps().campaignFundsChangedOnFunds(campaignActive2, fixedSum));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6420")
    public void testSeveralPaysOneCampaign() {
        log.info("Оплата одной кампании дважды в одном вызове");
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaigns(
                new AxisError(354, AxisErrorDetails.PAYCAMPELEMENT_CAMPAIGNID_MUST_BE_UNIQUE),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                        .withCampaignID(activeCampaignID1)
                                        .withCurrency(CURRENCY)
                                        .withSum(sumWithVAT),
                                new PayCampElementMap(api.type())
                                        .withCampaignID(activeCampaignID1)
                                        .withCurrency(CURRENCY)
                                        .withSum(sumWithVAT))
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6419")
    public void testPayCampaignZeroSumToPay() {
        log.info("Оплата кампании по кредитному договору на сумму: 0уе");
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaigns(
                new AxisError(354, AxisErrorDetails.INVALID_AMOUNT_SPECIFIED_FOR_CAMPAIGN, activeCampaignID1),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                .withCampaignID(activeCampaignID1)
                                .withCurrency(Currency.RUB)
                                .withSum(0f))
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6427")
    public void testLessThenMinLimitSumPayCampaign() {
        MoneyCurrency rubCurrency = MoneyCurrency.get(Currency.RUB);
        log.info("Оплата кампании на сумму: " + sum);
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaigns(
                new AxisError(354, AxisErrorDetails.LOW_AMOUNT_SPECIFIED_FOR_CAMPAIGN_CUSTOM,
                        rubCurrency.getMinTransferAmount().stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                        rubCurrency.getAbbreviation("en").toLowerCase(), activeCampaignID1),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                .withCampaignID(activeCampaignID1)
                                .withCurrency(CURRENCY)
                                .withSum(Money.valueOf(sum.floatValue()).getPrevious().floatValue()))
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6428")
    public void sendEmptyPaymentToken() {
        log.info("Оплата кампании с пустым платежным токеном");
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaignsYM(
                new AxisError(350, AxisErrorDetails.FINANCIAL_TOKEN_NOT_SUBMITTED),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                .withCampaignID(activeCampaignID1)
                                .withCurrency(CURRENCY)
                                .withSum(sumWithVAT)),
                ""
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6429")
    public void sendInvalidPaymentToken() {
        log.info("Оплата кампании с невалидным платежным токеном");
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaignsYM(
                new AxisError(361, null),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                .withCampaignID(activeCampaignID1)
                                .withCurrency(CURRENCY)
                                .withSum(sumWithVAT)),
                "invalid"
        );
    }

    //@Test до починки ЯД DIRECT-65926
    @ru.yandex.qatools.allure.annotations.TestCaseId("6430")
    public void sendElsePaymentToken() {
        log.info("Оплата кампании с чужим платежным токеном");
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaignsYM(
                new AxisError(361, null),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                .withCampaignID(activeCampaignID1)
                                .withCurrency(CURRENCY)
                                .withSum(sumWithVAT)),
                User.get(FinanceLogins.OLD_OVERDRAFT_CLIENT).getPaymentToken()
        );
    }

//    @Test
//    public void testPayCampaignWithPaymentToken() {
//        log.info("Оплата активной кампании");
//        CampaignInfo campaignInfo = api.userSteps.campaignSteps().getCampaignParams(activeCampaignID);
//        int response = api.userSteps.financeSteps().payCampaigns(
//                PayMethod.OVERDRAFT,
//                null,
//                true,
//                new PayCampElementMap(api.type())
//                        .withCampaignID(activeCampaignID)
//                        .withSum(sum));
//        assertThat("Метод PayCampaigns вернул неуспешный код завершения операции", response, equalTo(1));
//        ConditionFactories.NOTIFY_ORDER2.until(
//                api.userSteps.campaignSteps().campaignSumChangedOnSum(new CampaignInfoMap(campaignInfo), sum));
//    }ToDo broken payment token - DIRECT-41294

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6431")
    public void testPayCampaignMoreThenOverdraftLimit() {
        log.info("Оплата кампании на сумму превыщающую лимит овердрафта для данного клиента");
        api.userSteps.financeSteps().shouldGetErrorOnPayCampaigns(
                new AxisError(364, null),
                new PayCampaignsInfoMap(api.type())
                        .withPayMethod(PayMethod.OVERDRAFT)
                        .withPayments(new PayCampElementMap(api.type())
                                .withCampaignID(activeCampaignID1)
                                .withCurrency(CURRENCY)
                                // коэффициент 1.1 пока не починят баг BALANCE-24127
                                .withSum(Money.valueOf(overdraftLimit * 1.1).getNext().floatValue()))
        );
    }
}
