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

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

import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
import com.yandex.direct.api.v5.campaigns.SmartCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.SmartCampaignSearchStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.SmartCampaignStrategy;
import com.yandex.direct.api.v5.campaigns.UpdateResponse;
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.CampMetrikaGoalsRecord;
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.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignSearchStrategyMap;
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.StrategyPayForConversionPerCampaignMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
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;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directapi.matchers.beans.version5.BeanDifferMatcherV5.beanDifferV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

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

    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    private static final Long goalId = MetrikaGoals.getGoalForCounter(counterId);

    private static final Money minCpa = MoneyCurrency.get(currency).getDefaultPrice(); //todo MIN_CPC_CPA_PERFORMANCE
    private static final Money maxPayForConversionCpa = MoneyCurrency.get(currency).getMaxPayForConversionCpa();
    private static final Money weekSpendLimit = Money.valueOf(100000);
    @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 cpa;
    private SmartCampaignStrategyMap strategyMap;
    private Long campaignId;

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {"Значение больше минимального", minCpa.getNext().bidLong().longValue()},
                {"Минимальное значение", minCpa.bidLong().longValue()},
                {"Максимальное значение", maxPayForConversionCpa.bidLong().longValue()}
        };
        return Arrays.asList(data);
    }

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

        List<CampMetrikaGoalsRecord> campaignGoals = api.userSteps.getDirectJooqDbSteps().useShard(shard)
                .campMetrikaGoalsSteps().getCampMetrikaGoalRecords(campaignId);
        if (campaignGoals.isEmpty()) {
            api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps()
                    .addCampMetrikaGoals(campaignId, goalId, 100L, 100L);
        }

        strategyMap = new SmartCampaignStrategyMap()

                .withSearch(new SmartCampaignSearchStrategyMap()
                        .withBiddingStrategyType(SmartCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_PER_CAMPAIGN)
                        .withPayForConversionPerCampaign(new StrategyPayForConversionPerCampaignMap()
                                .withWeeklySpendLimit(weekSpendLimit.bidLong().longValue())
                                .withGoalId(goalId)
                                .withCpa(cpa)))
                .withNetwork(new SmartCampaignNetworkStrategyMap().defaultServingOff());
    }

    @Test
    public void averageCpaTest() {
        UpdateResponse response = api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                .withCounterId(counterId.longValue())
                                .withBiddingStrategy(strategyMap))),
                ExpectedResult.success());
        assumeThat("получили результаты обновления кампании", response.getUpdateResults(), hasSize(1));

        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(response.getUpdateResults().get(0).getId()))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withSmartCampaignFieldNames(SmartCampaignFieldEnum.BIDDING_STRATEGY));
        assumeThat("получили кампанию", campaigns, hasSize(1));
        SmartCampaignStrategy actualStrategy = campaigns.get(0).getSmartCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());

        assertThat("получили корректные стратегии", actualStrategy,
                beanDifferV5((SmartCampaignStrategy) strategyMap.getBean()));
    }
}
