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

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

import com.google.gson.JsonElement;
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.models.jooq.ppc.tables.records.CampaignsRecord;
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.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.PriorityGoalsItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpaAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpaMap;
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.TextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyMap;
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.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.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.hazelcast.SemaphoreRule;

@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@RunWith(Parameterized.class)
@Description("Cценарии проверки параметра GoalId при обновлении кампании со стратегией AverageCpa")
//Тест проверяет валидацию целей с включенной фичей disable_all_goals_optimization_for_dna
@Tag(TagDictionary.TRUNK)
public class StrategyAverageCpaGoalIdTest {
    private static final String client = CampaignsLogins.CLIENT_NEW_FEATURES;
    private static final Currency currency = Currency.RUB;

    private static final Money minAverageCpa = MoneyCurrency.get(currency).getMinAveragePrice().bidLong();
    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    private static final Long[] goals = MetrikaGoals.getConterGoalIds(counterId, 1);
    private static final Long ALL_GOALS = 0L;
    private static final Long MEANINGFULL_GOALS = 13L;
    @ClassRule
    public static ApiSteps api = new ApiSteps().as(client);
    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();
    private static Long campaignId;
    @Rule
    public Trashman trasher = new Trashman(api);
    @Parameterized.Parameter(value = 0)
    public String description;
    @Parameterized.Parameter(value = 1)
    public Long initialGoalId;
    @Parameterized.Parameter(value = 2)
    public Long newGoalId;
    @Parameterized.Parameter(value = 3)
    public ExpectedResult expectedResult;

    private DirectJooqDbSteps jooqDbSteps;

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {"По всем целям (цель не изменилась)", ALL_GOALS, ALL_GOALS,
                        ExpectedResult.success()},
                {"По конкретной цели -> По всем целям", goals[0], ALL_GOALS,
                        ExpectedResult.errors(new Notification(4000,
                                Api5ErrorDetails.ALL_GOALS_OPTIMIZATION_IS_PROHIBITED))},
                {"По ключевым целям", goals[0], MEANINGFULL_GOALS,
                        ExpectedResult.errors(new Notification(4000,
                                Api5ErrorDetails.SPECIFIED_GOAL_NOT_FOUND))},
                {"По конкретной цели (цель не изменилась)", goals[0], goals[0],
                        ExpectedResult.success()},
        };
        return Arrays.asList(data);
    }

    @Before
    public void prepare() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        int shard = api.userSteps.clientFakeSteps().getUserShard(client);
        jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);

        campaignId = api.userSteps.campaignSteps().addCampaign(
                new CampaignAddItemMap().defaultCampaignAddItem().withDefaultTextCampaign()
                        .withTextCampaign(new TextCampaignAddItemMap()
                                .withCounterIds(counterId)
                                .withPriorityGoals(new PriorityGoalsItemMap().withGoalId(goals[0]).withValue(125_000_000L))
                                .withBiddingStrategy(new TextCampaignStrategyAddMap()
                                        .withSearch(new TextCampaignSearchStrategyAddMap()
                                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_CPA)
                                                .withAverageCpa(new StrategyAverageCpaAddMap()
                                                        .withAverageCpa(minAverageCpa.longValue())
                                                        .withGoalId(goals[0])))
                                        .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultServingOff())))
        );

        //поскольку создание кампании с goal_id=0 запрещено, создаем с конретной целью, а затем меняем через dbSteps.
        fakeUpdateStrategyDataGoalId(initialGoalId);
    }

    private void fakeUpdateStrategyDataGoalId(Long newGoalId) {
        CampaignsRecord campaign = jooqDbSteps.campaignsSteps().getCampaignById(campaignId);
        JsonElement strategyData = campaign.getStrategyData();
        strategyData.getAsJsonObject().addProperty("goal_id", newGoalId);
        campaign.setStrategyData(strategyData);

        jooqDbSteps.campaignsSteps().updateCampaigns(campaign);
    }

    @Test
    public void updateGoalIdTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withTextCampaign(new TextCampaignUpdateItemMap()
                                .withBiddingStrategy(new TextCampaignStrategyMap()
                                        .withSearch(new TextCampaignSearchStrategyMap()
                                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_CPA)
                                                .withAverageCpa(new StrategyAverageCpaMap()
                                                        .withAverageCpa(minAverageCpa.longValue())
                                                        .withGoalId(newGoalId)))
                                        .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff())))),
                expectedResult);
    }
}
