package ru.yandex.autotests.directintapi.bstransport.main.campaign.parameters.strategy.search;

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

import com.yandex.direct.api.v5.campaigns.MobileAppCampaignSearchStrategyTypeEnum;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.aqua.annotations.project.Feature;
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.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
import ru.yandex.autotests.directapi.darkside.model.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.bslogs.AutoBudget;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignSearchStrategyMap;
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.UpdateRequestMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.StoriesNames;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directintapi.bstransport.TransportUtils.MOBILE_APP_INSTALL_GOAL_ID;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

/**
 * https://st.yandex-team.ru/TESTIRT-10613
 */
@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Description("Транспорт: проверка отправки параметра AutoBudgetGoalID для стратегии AVERAGE_CPI на поиске")
@Stories(StoriesNames.CAMPAIGN_PARAMS_STRATEGY)
@Feature(FeatureNames.CAMPAIGNS)
public class BsTransportOfAutoBudgetForAverageCPIStrategySearchTest {
    private static final Money WEEKLY_BUDGET = MoneyCurrency.get(Currency.RUB).getMinWeeklyBudgetAmount().addVAT();
    private static final Money AVERAGE_CPI = MoneyCurrency.get(Currency.RUB)
            .getMinAverageConversionPrice().multiply(2L).addVAT();
    private static final Money BID_CEILING = MoneyCurrency.get(Currency.RUB)
            .getMinAverageConversionPrice().multiply(3L);

    private static final String LOGIN = Logins.LOGIN_RUB;

    private static Campaign campaign;

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

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

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

    @BeforeClass
    public static void beforeClass() {
        Integer shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        Long cid = api.userSteps.campaignSteps().addDefaultMobileAppCampaign();
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);

        Long pid = api.userSteps.adGroupsSteps().addDefaultMobileGroup(cid);
        Long bid = api.userSteps.adsSteps().addDefaultMobileAppAd(pid);
        Long keywordId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);
        MobileAppCampaignSearchStrategyMap searchStrategy =
                new MobileAppCampaignSearchStrategyMap()
                        .withBiddingStrategyType(MobileAppCampaignSearchStrategyTypeEnum.AVERAGE_CPI)
                        .withAverageCpi(new StrategyAverageCpiMap()
                                .defaultStrategyAverageCpi(Currency.RUB)
                                .withWeeklySpendLimit(WEEKLY_BUDGET.subtractVAT().bidLong().longValue())
                                .withBidCeiling(BID_CEILING.bidLong().longValue())
                                .withAverageCpi(AVERAGE_CPI.subtractVAT().bidLong().longValue()));
        MobileAppCampaignNetworkStrategyMap networkStrategy =
                new MobileAppCampaignNetworkStrategyMap().defaultServingOff();
        api.userSteps.campaignSteps().campaignsUpdate(
                new UpdateRequestMap().withCampaigns(
                        new CampaignUpdateItemMap().withId(cid).withMobileAppCampaign(
                                new MobileAppCampaignUpdateItemMap().withBiddingStrategy(
                                        new MobileAppCampaignStrategyMap().withSearch(searchStrategy).withNetwork(networkStrategy)
                                )
                        )
                )
        );
        RunBsTransportScriptResponse resp =
                api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, cid);
        assumeThat("кампания была отправлена", campaign, notNullValue());
    }

    @Test
    public void testTransportOfAutoBudgetForAverageCPISearch() {
        assertThat("отправленный в БК параметр AutoBudget соответствует ожидаемому",
                campaign.getAutoBudget(), equalTo(AutoBudget.YES.transportValue()));
    }

    @Test
    public void testTransportOfAutoBudgetGoalIdForAverageCPISearch() {
        assertThat("отправленный в БК параметр AutoBudgetGoalID соответствует ожидаемому",
                campaign.getAutoBudgetGoalId(), equalTo(MOBILE_APP_INSTALL_GOAL_ID));
    }

    @Test
    public void testTransportOfAutoBudgetMaxBidCurForAverageCPISearch() {
        assertThat("отправленный в БК параметр AutoBudgetMaxBidCur соответствует ожидаемому",
                campaign.getAutoBudgetMaxBidCur(), equalTo(BID_CEILING.floatValue()));
    }

    @Test
    public void testTransportOfAutoBudgetWeekLimitCurForAverageCPISearch() {
        assertThat("отправленный в БК параметр AutoBudgetWeekLimitCur соответствует ожидаемому",
                campaign.getAutoBudgetWeekLimitCur(), equalTo(WEEKLY_BUDGET.floatValue()));
    }

    @Test
    public void testTransportOfAutoBudgetAvgCPACurForAverageCPISearch() {
        assertThat("отправленный в БК параметр AutoBudgetAvgCPACur соответствует ожидаемому",
                campaign.getAutoBudgetAvgCPACur(), equalTo(AVERAGE_CPI.floatValue()));
    }

    @Test
    public void testTransportOfTargetTypeAverageCPISearch() {
        List<Integer> expectedTargetType = Arrays.asList(3);
        assertThat("отправленный в БК параметр ShowCondition.TargetType соответствует ожидаемому",
                campaign.getShowCondition().getTargetType(), beanDiffer(expectedTargetType));
    }
}
