package ru.yandex.autotests.direct.api.campaigns.update.textcampaign.strategy.averageroi;

import java.util.Arrays;
import java.util.Collection;

import com.yandex.direct.api.v5.campaigns.TextCampaignSearchStrategyTypeEnum;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.api.campaigns.CampaignsFeatures;
import ru.yandex.autotests.direct.api.campaigns.CampaignsLogins;
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.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetailsJava;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageRoiMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.JavaOrPerlExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
import ru.yandex.autotests.directapi.model.campaigns.MetrikaGoals;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

/**
 * Created by chicos on 02.09.2015.
 */
@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@RunWith(Parameterized.class)
@Description("Негативные сценарии проверки параметра WeeklySpendLimit при обновлении кампании со стратегией AverageRoi")
@Tag(TagDictionary.TRUNK)
public class StrategyAverageRoiWeeklySpendLimitNegativeTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;
    private static MoneyCurrency moneyCurrency = MoneyCurrency.get(currency);
    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    private static final Long goalId = MetrikaGoals.getGoalForCounter(counterId);
    private Long campaignId;

    private static final Money minLimit = moneyCurrency.getMinWeeklyBudgetAmount();
    private static final Money maxLimit = moneyCurrency.getMaxWeeklyBudgetAmount();

    private TextCampaignStrategyMap strategyMap;

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(client);

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

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

    @Parameterized.Parameter(value = 0)
    public String description;

    @Parameterized.Parameter(value = 1)
    public StrategyAverageRoiMap params;

    @Parameterized.Parameter(value = 2)
    public JavaOrPerlExpectedResult expectedResult;

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {"Нулевое значение", new StrategyAverageRoiMap().withWeeklySpendLimit(0L), JavaOrPerlExpectedResult
                        .java(ExpectedResult.errors(
                                new Notification(4000,
                                        Api5ErrorDetailsJava.VALUE_MUST_NOT_BE_LESS_WITHOUT_CURRENCY,
                                        "WeeklySpendLimit",
                                        minLimit.stringValue(MoneyFormat.WITHOUT_EXTRA_ZEROS))))
                        .perl(ExpectedResult.errors(
                                new Notification(4000,
                                        Api5ErrorDetails.WEEKLY_LIMIT_SHOULD_BE_MORE_THAN,
                                        minLimit.stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                                        moneyCurrency.getApiDescription())))},
                {"Отрицательное значение", new StrategyAverageRoiMap().withWeeklySpendLimit(-1L), JavaOrPerlExpectedResult
                        .java(ExpectedResult.errors(
                                new Notification(4000,
                                        Api5ErrorDetailsJava.VALUE_MUST_NOT_BE_LESS_WITHOUT_CURRENCY,
                                        "WeeklySpendLimit",
                                        minLimit.stringValue(MoneyFormat.WITHOUT_EXTRA_ZEROS))))
                        .perl(ExpectedResult.errors(
                                new Notification(4000,
                                        Api5ErrorDetails.WEEKLY_LIMIT_SHOULD_BE_MORE_THAN,
                                        minLimit.stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                                        moneyCurrency.getApiDescription())))},
                {"Значение меньше минимального",
                        new StrategyAverageRoiMap().withWeeklySpendLimit(minLimit.getPrevious().bidLong().longValue()),
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(
                                        new Notification(4000,
                                                Api5ErrorDetailsJava.VALUE_MUST_NOT_BE_LESS_WITHOUT_CURRENCY,
                                                "WeeklySpendLimit",
                                                minLimit.stringValue(MoneyFormat.WITHOUT_EXTRA_ZEROS))))
                                .perl(ExpectedResult.errors(
                                        new Notification(4000,
                                                Api5ErrorDetails.WEEKLY_LIMIT_SHOULD_BE_MORE_THAN,
                                                minLimit.stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                                                moneyCurrency.getApiDescription())))},
                {"Значение больше максимального",
                        new StrategyAverageRoiMap().withWeeklySpendLimit(maxLimit.getNext().bidLong().longValue()),
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetailsJava.VALUE_MUST_NOT_BE_GREATER_THAN,
                                        "WeeklySpendLimit",
                                        maxLimit.stringValue(MoneyFormat.WITHOUT_EXTRA_ZEROS))))
                                .perl(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetails.WEEKLY_LIMIT_IS_TOO_HIGH,
                                        maxLimit.stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                                        moneyCurrency.getApiDescription())))},
                {"Значение бюджета меньше максимальной ставки",
                        new StrategyAverageRoiMap()
                                .withWeeklySpendLimit(minLimit.bidLong().longValue())
                                .withBidCeiling(MoneyCurrency.get(currency).getMaxPrice().bidLong().longValue()),
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetailsJava.MUST_BE_LESS_THAN_OR_EQUAL_TO_WEEKLY_BUDGET,
                                        "BidCeiling")))
                                .perl(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetails.WEEKLY_BUDGET_MUST_BE_GREATER_THAN_MAXIMUM_BID)))},
        };
        return Arrays.asList(data);
    }

    @Before
    @Step("Подготовим данные для теста")
    public void clearUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        int shard = api.userSteps.clientFakeSteps().getUserShard(client);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps()
                .addCampMetrikaGoals(campaignId, goalId, 100L, 100L);

        strategyMap = new TextCampaignStrategyMap()
                .withSearch(new TextCampaignSearchStrategyMap()
                        .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_ROI)
                        .withAverageRoi(params
                                .defaultStrategyAverageRoi()
                                .withGoalId(goalId)))
                .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff());
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("1153")
    public void weeklyLimitNegativeTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withTextCampaign(new TextCampaignUpdateItemMap()
                                .withBiddingStrategy(strategyMap))),
                expectedResult);
    }
}
