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

import java.math.BigDecimal;

import com.yandex.direct.api.v5.campaigns.SmartCampaignSearchStrategyTypeEnum;
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.beans.campaign.StrategyData;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsStrategyName;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampaignsRecord;
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.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.StrategyPayForConversionPerFilterMap;
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 ru.yandex.autotests.direct.api.campaigns.CampaignCommonMatchers.strategyDataCompareStrategy;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

/**
 * Тест работает с включенными фичей cpa_pay_for_conversions_extended_mode
 */
@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@Description("Cценарии проверки при обновлении стратегии на PayForConversionPerCamp и PayForConversionPerFilter")
@Tag(TagDictionary.TRUNK)
public class StrategyPayForConversionDbTest {
    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 cpa = MoneyCurrency.get(currency).getMaxPayForConversionCpa();
    private static final Money weekSpendLimit = Money.valueOf(10000);

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(client);
    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();
    @Rule
    public Trashman trasher = new Trashman(api);
    private Long campaignId;
    private DirectJooqDbSteps dbSteps;

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

        dbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);
        dbSteps.campMetrikaGoalsSteps()
                .addOrUpdateMetrikaGoals(campaignId, goalId, 100L, 100L);
    }

    @Test
    public void updateStrategyToPayForConversionPerCampTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                .withCounterId(counterId.longValue())
                                .withBiddingStrategy(new SmartCampaignStrategyMap()
                                        .withSearch(new SmartCampaignSearchStrategyMap()
                                                .withBiddingStrategyType(SmartCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_PER_CAMPAIGN)
                                                .withPayForConversionPerCampaign(new StrategyPayForConversionPerCampaignMap()
                                                        .withWeeklySpendLimit(weekSpendLimit.bidLong().longValue())
                                                        .withGoalId(goalId)
                                                        .withCpa(cpa.bidLong().longValue())))
                                        .withNetwork(new SmartCampaignNetworkStrategyMap().defaultServingOff())))),
                ExpectedResult.success());

        CampaignsRecord campaignsRecord = dbSteps.campaignsSteps().getCampaignById(campaignId);

        CampaignsRecord expextedCampaignsRecord = new CampaignsRecord();
        expextedCampaignsRecord.setCid(campaignId);
        expextedCampaignsRecord.setStrategyName(CampaignsStrategyName.autobudget_avg_cpa_per_camp);
        expextedCampaignsRecord.setStrategyData(new StrategyData()
                .withSum(weekSpendLimit.doubleValue())
                .withName(CampaignsStrategyName.autobudget_avg_cpa_per_camp)
                .withGoalId(goalId.toString())
                .withAvgCpa(cpa.doubleValue())
                .withPayForConversion(1)
                .withVersion(1)
                .toJsonElement());
        assertThat("стратегия правильно сохранилась в базе", campaignsRecord.intoMap(),
                beanDiffer(expextedCampaignsRecord.intoMap())
                        .useCompareStrategy(strategyDataCompareStrategy));
    }

    @Test
    public void updateStrategyToPayForConversionPerFilterTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                .withCounterId(counterId.longValue())
                                .withBiddingStrategy(new SmartCampaignStrategyMap()
                                        .withSearch(new SmartCampaignSearchStrategyMap()
                                                .withBiddingStrategyType(SmartCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_PER_FILTER)
                                                .withPayForConversionPerFilter(new StrategyPayForConversionPerFilterMap()
                                                        .withWeeklySpendLimit(weekSpendLimit.bidLong().longValue())
                                                        .withGoalId(goalId)
                                                        .withCpa(cpa.bidLong().longValue())))
                                        .withNetwork(new SmartCampaignNetworkStrategyMap().defaultServingOff())))),
                ExpectedResult.success());

        CampaignsRecord campaignsRecord = dbSteps.campaignsSteps().getCampaignById(campaignId);

        CampaignsRecord expextedCampaignsRecord = new CampaignsRecord();
        expextedCampaignsRecord.setCid(campaignId);
        expextedCampaignsRecord.setStrategyName(CampaignsStrategyName.autobudget_avg_cpa_per_filter);
        expextedCampaignsRecord.setStrategyData(new StrategyData()
                .withSum(weekSpendLimit.doubleValue())
                .withName(CampaignsStrategyName.autobudget_avg_cpa_per_filter)
                .withGoalId(goalId.toString())
                .withFilterAvgCpa(BigDecimal.valueOf(cpa.doubleValue()))
                .withPayForConversion(1)
                .withVersion(1)
                .toJsonElement());
        assertThat("стратегия правильно сохранилась в базе", campaignsRecord.intoMap(),
                beanDiffer(expextedCampaignsRecord.intoMap())
                        .useCompareStrategy(strategyDataCompareStrategy));
    }
}
