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

/**
 * Created by pavryabov on 19.11.14.
 * https://st.yandex-team.ru/TESTIRT-2839
 */

import org.junit.AfterClass;
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.httpclient.data.sandbox.APISandboxClientTypeEnum;
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.directapi.ApiFeatures;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.common.api45.Account;
import ru.yandex.autotests.directapi.common.api45.AccountManagementResponse;
import ru.yandex.autotests.directapi.common.api45.ShortClientInfo;
import ru.yandex.autotests.directapi.model.finances.PaymentMap;
import ru.yandex.autotests.directapi.model.finances.sharedaccount.AccountMap;
import ru.yandex.autotests.directapi.model.finances.sharedaccount.TransferMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directapi.sandbox.SandboxLogins;
import ru.yandex.autotests.directapi.steps.ConditionFactories;
import ru.yandex.autotests.directapi.steps.finance.FinanceSteps;
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.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Features(ApiFeatures.SANDBOX)
public class AccountManagementAgencyTest {
    private static LogSteps log = LogSteps.getLogger(AccountManagementAgencyTest.class);

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

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

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

    private static final String agency = SandboxLogins.SANDBOX_INIT_CLIENT8;
    private static int accountID1;
    private static int accountID2;
    private static String subclient1;
    private static String subclient2;
    Money minInvoiceAmount = MoneyCurrency.get(Currency.RUB).getMinInvoiceAmount().addVAT();

    @BeforeClass
    public static void initSandbox() {
        api.as(agency).userSteps.sandboxSteps()
                .enableSandboxByApi(agency, APISandboxClientTypeEnum.AGENCY, true, Currency.RUB, false);
        ShortClientInfo[] clients = api.userSteps.clientSteps().getSubClients(agency);
        assumeThat("агентство имеет несколько субклиентов", clients.length, greaterThan(1));

        subclient1 = clients[0].getLogin();
        subclient2 = clients[1].getLogin();

        log.info("Подождем активации кампаний в Песочнице");
        ConditionFactories.SANDBOX_STATUS.until(api.userSteps.campaignSteps().hasOnCampaign(subclient1));
        ConditionFactories.SANDBOX_STATUS.until(api.userSteps.campaignSteps().hasOnCampaign(subclient2));

        api.userSteps.financeSteps().enableSharedAccount(subclient1);
        accountID1 = api.userSteps.financeSteps().getAccountID(subclient1);

        api.userSteps.financeSteps().enableSharedAccount(subclient2);
        accountID2 = api.userSteps.financeSteps().getAccountID(subclient2);
    }

    @Test
    public void checkAccountManagementUpdate() {
        Account account = api.userSteps.financeSteps().getAccount(accountID1);
        AccountManagementResponse response = api.userSteps.financeSteps().update(new AccountMap(account));
        assumeThat("AccountManagement.update вернул непустой результат",
                response.getActionsResult().length, greaterThan(0));
        int accountIDAfterUpdate = response.getActionsResult()[0].getAccountID();
        assertThat("метод AccountManagement.update успешно завершился", accountIDAfterUpdate, equalTo(accountID1));
    }

    @Test
    public void checkAccountManagementInvoice() {
        PaymentMap payment = new PaymentMap(api.type())
                .withAccountID(accountID1)
                .withCurrency(Currency.RUB)
                .withAmount(minInvoiceAmount.floatValue());
        AccountManagementResponse response = api.userSteps.financeSteps().invoiceInSandbox(payment);
        assumeThat("AccountManagement.invoice вернул непустой результат",
                response.getActionsResult().length, greaterThan(0));
        assertThat("сформирован корректный URL выставленного счета",
                response.getActionsResult()[0].getURL(), containsString("request_id"));
    }

    @Test
    public void checkAccountManagementDeposit() {
        //DIRECT-36190
        Account account = api.userSteps.financeSteps().getAccount(accountID1);
        PaymentMap payment = new PaymentMap(api.type())
                .withAccountID(accountID1)
                .withCurrency(Currency.RUB)
                .withAmount(minInvoiceAmount.floatValue())
                .withContract(FinanceSteps.SANDBOX_CONTRACT);
        AccountManagementResponse response = api.userSteps.financeSteps().depositInSandbox(payment);
        assumeThat("AccountManagement.deposit вернул непустой результат",
                response.getActionsResult().length, greaterThan(0));
        assertThat("AccountManagement.deposit вернул правильный результат",
                response.getActionsResult()[0].getAccountID(), equalTo(accountID1));
        ConditionFactories.SANDBOX_STATUS.until(
                api.userSteps.financeSteps().accountAmountChangedOnSum(
                        account, minInvoiceAmount.subtractVAT().floatValue(), true));
    }

    @Test
    public void checkAccountManagementTransfer() {
        //DIRECT-36190
        Account accountFrom = api.userSteps.financeSteps().getAccount(accountID1);
        Account accountTo = api.userSteps.financeSteps().getAccount(accountID2);
        TransferMap transferMap = new TransferMap(api.type())
                .withFromAccountID(accountID1)
                .withToAccountID(accountID2)
                .withCurrency(Currency.RUB)
                .withAmount(minInvoiceAmount.floatValue());
        AccountManagementResponse response = api.userSteps.financeSteps().transferInSandbox(transferMap);
        assumeThat("AccountManagement.transfer вернул непустой результат",
                response.getActionsResult().length, greaterThan(0));
        assertThat("AccountManagement.transfer вернул правильный результат",
                response.getActionsResult()[0].getAccountID(), equalTo(accountID1));
        ConditionFactories.SANDBOX_STATUS.until(
                api.userSteps.financeSteps().accountAmountChangedOnSum(accountFrom, -minInvoiceAmount.floatValue(), true));
        ConditionFactories.SANDBOX_STATUS.until(
                api.userSteps.financeSteps().accountAmountChangedOnSum(accountTo, minInvoiceAmount.floatValue(), true));
    }

    @AfterClass
    public static void closeSandbox() {
        api.userSteps.sandboxSteps().closeSandbox(agency);
    }
}
