package ru.yandex.autotests.direct.api.campaigns.add.textcampaign.strategy.payforconversion;

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

import com.yandex.direct.api.v5.campaigns.AddResponse;
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.db.steps.DirectJooqDbSteps;
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.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.model.User;
import ru.yandex.autotests.directapi.model.api5.campaigns.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
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;
/*
 *Тест работает с включенными фичей cpa_pay_for_conversions_extended_mode
 */

@Aqua.Test
@Features(CampaignsFeatures.ADD)
@RunWith(Parameterized.class)
@Description("Негативные сценарии проверки параметра GoalId при создании кампании со стратегией PayForConversion")
@Tag(TagDictionary.TRUNK)
public class StrategyPayForConversionGoalIdNegativeTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;

    private static final Money minAverageCpa = MoneyCurrency.get(currency).getMinAveragePrice();
    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    @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 Long goalId;
    @Parameterized.Parameter(value = 2)
    public ExpectedResult expectedResult;

    private TextCampaignStrategyMap expectedStrategyMap;

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Long[] goalIds = MetrikaGoals.getConterGoalIds(counterId, 1);
        Object[][] data = new Object[][]{
                {"По всем целям", 0L, ExpectedResult.errorsIgnoringDetails(new Notification(4000,
                        Api5ErrorDetails.PAY_FOR_CONVERSIOIN_DOES_NOT_ALLOW_ALL_GOALS_OPTIMIZATION))},
                {"Цель к которой нет доступа", 62047749L, ExpectedResult.errorsIgnoringDetails(new Notification(4000,
                        Api5ErrorDetails.SPECIFIED_GOAL_NOT_FOUND))},
                {"Ключевые цели", 13L, ExpectedResult.errorsIgnoringDetails(new Notification(4000,
                        Api5ErrorDetails.SPECIFIED_GOAL_NOT_FOUND))},
        };
        return Arrays.asList(data);
    }

    @Before
    @Step("Подготовим данные для теста")
    public void clearUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);

        //проверяем фичу
        DirectJooqDbSteps dbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(client);
        Long clientId = Long.parseLong(User.get(client).getClientID());
        dbSteps.featuresSteps().ensureClientHasFeatureIfNotSet(clientId, "cpa_pay_for_conversions_extended_mode");
    }

    @Test
    public void payForConversionWithoutCounterGoalIdNegativeTest() {
        AddResponse response = api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withTextCampaign(new TextCampaignAddItemMap()
                                .withBiddingStrategy(new TextCampaignStrategyAddMap()
                                        .withSearch(new TextCampaignSearchStrategyAddMap()
                                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION)
                                                .withPayForConversion(new StrategyPayForConversionAddMap()
                                                        .withCpa(minAverageCpa.getNext().bidLong().longValue())
                                                        .withGoalId(goalId)
                                                        .withWeeklySpendLimit(null)))
                                        .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultServingOff())))),
                expectedResult);

    }

    @Test
    public void payForConversionGoalIdNegativeTest() {
        AddResponse response = api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withTextCampaign(new TextCampaignAddItemMap()
                                .withCounterIds(counterId)
                                .withBiddingStrategy(new TextCampaignStrategyAddMap()
                                        .withSearch(new TextCampaignSearchStrategyAddMap()
                                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION)
                                                .withPayForConversion(new StrategyPayForConversionAddMap()
                                                        .withCpa(minAverageCpa.getNext().bidLong().longValue())
                                                        .withGoalId(goalId)
                                                        .withWeeklySpendLimit(null)))
                                        .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultServingOff())))),
                expectedResult);
    }
}
