package ru.yandex.autotests.direct.api.campaigns.update.textcampaign.strategy.averagecpa;

import com.yandex.direct.api.v5.campaigns.TextCampaignSearchStrategyTypeEnum;
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.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.StrategyAverageCpaMap;
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 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;

@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@Description("Проверка сохранения в базу стратегии AverageCpa")
@Issue("https://st.yandex-team.ru/DIRECT-70914")
@Tag(TagDictionary.TRUNK)
public class StrategyAverageCpaDbTest {

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

    private static final Money BID_CEILING = MoneyCurrency.get(CURRENCY).getMinAveragePrice().getNext();
    private static final Money AVERAGE_CPA = MoneyCurrency.get(CURRENCY).getMinAveragePrice();
    private static final Money WEEKLY_SPEND_LIMIT =
            MoneyCurrency.get(CURRENCY).getMaxWeeklyBudgetAmount().divide(10f);
    private static final Long GOAL_ID = MetrikaGoals.getGoalsForLogin(CLIENT, 1).get(0);

    private Long cid;
    private int shard;

    @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();
        api.userSteps.getDirectJooqDbSteps().useShard(shard).campMetrikaGoalsSteps()
                .addOrUpdateMetrikaGoals(cid, GOAL_ID, 100L, 100L);
        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()
                                                        .withWeeklySpendLimit(WEEKLY_SPEND_LIMIT.bidLong().longValue())
                                                        .withGoalId(GOAL_ID)
                                                        .withBidCeiling(BID_CEILING.bidLong().longValue())
                                                        .withAverageCpa(AVERAGE_CPA.bidLong().longValue())))
                                        .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff())))),
                ExpectedResult.success());
    }

    @Test
    public void saveInDbTest() {
        CampaignsRecord campaignsRecord =
                api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps().getCampaignById(cid);
        CampaignsRecord expextedCampaignsRecord = new CampaignsRecord();
        expextedCampaignsRecord.setCid(cid);
        expextedCampaignsRecord.setStrategyName(CampaignsStrategyName.autobudget_avg_cpa);
        expextedCampaignsRecord.setStrategyData(new StrategyData()
                .withSum(WEEKLY_SPEND_LIMIT.doubleValue())
                .withBid(BID_CEILING.doubleValue())
                .withName(CampaignsStrategyName.autobudget_avg_cpa)
                .withGoalId(GOAL_ID.toString())
                .withAvgCpa(AVERAGE_CPA.doubleValue())
                .withPayForConversion(0)
                .withVersion(1)
                .toJsonElement());
        assertThat("стратегия правильно сохранилась в базе", campaignsRecord.intoMap(),
                beanDiffer(expextedCampaignsRecord.intoMap())
                        .useCompareStrategy(strategyDataCompareStrategy));
    }
}
