package ru.yandex.autotests.direct.api.campaigns.get.textcampaign;

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.TextCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignSearchStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignStrategy;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

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.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.StrategyAverageCpaMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionMap;
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.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.Issue;
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.GET)
@Description("Проверка чтения стратегии с установленной оплатой за конверсии")
@Issue("https://st.yandex-team.ru/DIRECT-104313")
@Tag(TagDictionary.TRUNK)
public class GetCampaignStrategyAverageCpaWithPayForConversionSetTest {

    private static final String CLIENT = CampaignsLogins.CLIENT;
    private static final Currency CURRENCY = Currency.RUB;

    private static final Money AVERAGE_CPA = MoneyCurrency.get(CURRENCY).getMinAveragePrice();
    private static final Long GOAL_ID = MetrikaGoals.getGoalForLogin(CLIENT);

    private Long cid;
    private int shard;

    private TextCampaignStrategyMap expectedStrategyMap;

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

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

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

    @Before
    @Step("Подготовим данные для теста")
    public void prepareData() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);
        shard = api.userSteps.clientFakeSteps().getUserShard(CLIENT);
        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        DirectJooqDbSteps dbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);
        dbSteps.campMetrikaGoalsSteps()
                .addOrUpdateMetrikaGoals(cid, GOAL_ID, 100L, 100L);

        expectedStrategyMap = new TextCampaignStrategyMap()
                .withSearch(new TextCampaignSearchStrategyMap()
                        .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION)
                        .withPayForConversion(new StrategyPayForConversionMap()
                                .withCpa(AVERAGE_CPA.bidLong().longValue())
                                .withGoalId(GOAL_ID)
                                .withWeeklySpendLimit(null)))
                .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff());

        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(cid)
                        .withTextCampaign(new TextCampaignUpdateItemMap()
                                .withBiddingStrategy(new TextCampaignStrategyMap()
                                        .withSearch(new TextCampaignSearchStrategyMap()
                                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_CPA)
                                                .withAverageCpa(new StrategyAverageCpaMap()
                                                        .withAverageCpa(AVERAGE_CPA.bidLong().longValue())
                                                        .withGoalId(GOAL_ID)
                                                        .withBidCeiling(null)
                                                        .withWeeklySpendLimit(null)))
                                        .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff())))),
                ExpectedResult.success());

        //установка галки "оплата за конверсии" через web
        dbSteps.campaignsSteps().setStrategyDataPayForConversion(cid, 1L);
    }

    @Test
    public void strategyWithpayForConversionGetTest() {
        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(cid))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withTextCampaignFieldNames(TextCampaignFieldEnum.BIDDING_STRATEGY));
        assumeThat("получили кампанию", campaigns, hasSize(1));
        TextCampaignStrategy actualStrategy = campaigns.get(0).getTextCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());

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