package ru.yandex.autotests.direct.api.campaigns.update.mobilecampaign.strategy.averagecpi;

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.MobileAppCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.MobileAppCampaignNetworkStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.MobileAppCampaignSearchStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.MobileAppCampaignStrategy;
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 ru.yandex.aqua.annotations.project.Aqua;
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.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.CampaignAddItemMap;
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.MobileAppCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpiMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyNetworkDefaultAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
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.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;

/**
 * Тест работает с включенными фичами cpa_pay_for_conversions_mobile_apps_allowed
 */
@Aqua.Test
@Description("Временная проверка работы с полем pay_for_conversion, пока оно не поддержано в апи")
@Issue("https://st.yandex-team.ru/DIRECT-124918")
@Tag(TagDictionary.TRUNK)
public class StrategyAverageCpiWhenPayForConversionWasSetTest {

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

    private Long cid;

    @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);
        int shard = api.userSteps.clientFakeSteps().getUserShard(CLIENT);
        DirectJooqDbSteps dbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);

        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);
        cid = api.userSteps.campaignSteps().addCampaign(new CampaignAddItemMap()
                .defaultCampaignAddItem()
                .withMobileAppCampaign(new MobileAppCampaignAddItemMap()
                        .withBiddingStrategy(new MobileAppCampaignStrategyAddMap()
                                .withSearch(new MobileAppCampaignSearchStrategyAddMap().defaultAverageCpi(CURRENCY))
                                .withNetwork(new MobileAppCampaignNetworkStrategyAddMap()
                                        .withBiddingStrategyType(MobileAppCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT)
                                        .withNetworkDefault(new StrategyNetworkDefaultAddMap())
                                )
                        )

                ));

        dbSteps.campaignsSteps().setStrategyDataPayForConversion(cid, 1L);
    }

    @Test
    @Description("Проверяем, что при на наличии поля pay_for_conversion, кампания обновляется корректно")
    public void averageCpiTest() {
        MobileAppCampaignStrategyMap strategyMap = new MobileAppCampaignStrategyMap()
                .withSearch(new MobileAppCampaignSearchStrategyMap()
                        .withBiddingStrategyType(MobileAppCampaignSearchStrategyTypeEnum.AVERAGE_CPI)
                        .withAverageCpi(new StrategyAverageCpiMap()
                                .withAverageCpi(MoneyCurrency.get(CURRENCY).getMinAveragePrice().bidLong().longValue())
                                .withWeeklySpendLimit(null)
                                .withBidCeiling(null)))
                .withNetwork(new MobileAppCampaignNetworkStrategyMap().defaultServingOff());

        UpdateResponse response = api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(cid)
                        .withMobileAppCampaign(new MobileAppCampaignUpdateItemMap()
                                .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)
                        .withMobileAppCampaignFieldNames(MobileAppCampaignFieldEnum.BIDDING_STRATEGY));
        assumeThat("получили кампанию", campaigns, hasSize(1));
        MobileAppCampaignStrategy actualStrategy = campaigns.get(0).getMobileAppCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());

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