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

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

import com.google.gson.JsonElement;
import com.yandex.direct.api.v5.campaigns.SmartCampaignSearchStrategyTypeEnum;
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.api5.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpaPerCampaignAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpaPerCampaignMap;
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 averageCpa = MoneyCurrency.get(currency).getMinAveragePrice().multiply(10).bidLong();
    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    private static final Long[] goals = MetrikaGoals.getConterGoalIds(counterId, 2);
    private static final Long ALL_GOALS = 0L;
    @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], goals[0],
                        ExpectedResult.success()},
                {"Цель 1 -> Цель 2", goals[0], goals[1],
                        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().withDefaultSmartCampaign(counterId)
                        .withSmartCampaign(new SmartCampaignAddItemMap()
                                .withCounterId(counterId.longValue())
                                .withBiddingStrategy(new SmartCampaignStrategyAddMap()
                                        .withSearch(new SmartCampaignSearchStrategyAddMap()
                                                .withBiddingStrategyType(SmartCampaignSearchStrategyTypeEnum.AVERAGE_CPA_PER_CAMPAIGN)
                                                .withAverageCpaPerCampaign(new StrategyAverageCpaPerCampaignAddMap()
                                                        .withAverageCpa(averageCpa.longValue())
                                                        .withGoalId(goals[0])))
                                        .withNetwork(new SmartCampaignNetworkStrategyAddMap().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)
                        .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                .withBiddingStrategy(new SmartCampaignStrategyMap()
                                        .withSearch(new SmartCampaignSearchStrategyMap()
                                                .withBiddingStrategyType(SmartCampaignSearchStrategyTypeEnum.AVERAGE_CPA_PER_CAMPAIGN)
                                                .withAverageCpaPerCampaign(new StrategyAverageCpaPerCampaignMap()
                                                        .withAverageCpa(averageCpa.longValue())
                                                        .withGoalId(newGoalId)))
                                        .withNetwork(new SmartCampaignNetworkStrategyMap().defaultServingOff())))),
                expectedResult);
    }
}
