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

import java.util.List;

import com.yandex.direct.api.v5.campaigns.AddResponse;
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 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.User;
import ru.yandex.autotests.directapi.model.api5.campaigns.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap;
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.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.StrategyPayForConversionPerFilterAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionPerFilterMap;
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;

/*
 *Тест работает с включенными фичей cpa_pay_for_conversions_extended_mode
 */
@Aqua.Test
@Features(CampaignsFeatures.ADD)
@Description("Позитивные сценарии проверки создания кампании со стратегией PayForConversionPerFilter")
@Tag(TagDictionary.TRUNK)
public class StrategyPayForConversionPerFilterTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;

    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    private static Long[] goals = MetrikaGoals.getConterGoalIds(counterId, 1);

    private static final Money cpa = 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);

    private SmartCampaignStrategyMap expectedStrategyMap;

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

        //проверяем фичу
        DirectJooqDbSteps dbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(client);
        Long clientId = Long.parseLong(User.get(client).getClientID());
        dbSteps.featuresSteps().ensureClientHasFeatureIfNotSet(clientId, "cpa_pay_for_conversions_extended_mode");

        expectedStrategyMap = new SmartCampaignStrategyMap()
                .withSearch(new SmartCampaignSearchStrategyMap()
                        .withBiddingStrategyType(SmartCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_PER_FILTER)
                        .withPayForConversionPerFilter(new StrategyPayForConversionPerFilterMap()
                                .withCpa(cpa.bidLong().longValue())
                                .withGoalId(goals[0])
                                .withWeeklySpendLimit(weekSpendLimit.bidLong().longValue())))
                .withNetwork(new SmartCampaignNetworkStrategyMap().defaultServingOff());
    }

    @Test
    public void payForConversionCreateTest() {
        AddResponse response = api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withSmartCampaign(new SmartCampaignAddItemMap()
                                .withCounterId(counterId.longValue())
                                .withBiddingStrategy(new SmartCampaignStrategyAddMap()
                                        .withSearch(new SmartCampaignSearchStrategyAddMap()
                                                .withBiddingStrategyType(SmartCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_PER_FILTER)
                                                .withPayForConversionPerFilter(new StrategyPayForConversionPerFilterAddMap()
                                                        .withCpa(cpa.bidLong().longValue())
                                                        .withGoalId(goals[0])
                                                        .withWeeklySpendLimit(weekSpendLimit.bidLong().longValue())))
                                        .withNetwork(new SmartCampaignNetworkStrategyAddMap().defaultServingOff())))),
                ExpectedResult.success());

        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(response.getAddResults().get(0).getId()))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withSmartCampaignFieldNames(SmartCampaignFieldEnum.BIDDING_STRATEGY));


        assumeThat("получили результаты обновления кампании", response.getAddResults(), hasSize(1));

        assumeThat("получили кампанию", campaigns, hasSize(1));
        SmartCampaignStrategy actualStrategy = campaigns.get(0).getSmartCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());

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