package ru.yandex.autotests.direct.api.campaigns.add.mobilecampaign.strategy.payforinstall;

import com.yandex.direct.api.v5.campaigns.AddResponse;
import com.yandex.direct.api.v5.campaigns.MobileAppCampaignSearchStrategyTypeEnum;
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.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap;
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.MobileAppCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForInstallAddMap;
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.autotests.irt.testutils.beandiffer2.comparestrategy.defaultcomparestrategy.DefaultCompareStrategies;
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.anything;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;
import static ru.yandex.autotests.irt.testutils.beandiffer2.beanfield.BeanFieldPath.newPath;

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

    private static final Money averageCpi = MoneyCurrency.get(currency).getMinAveragePrice();
    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 DirectJooqDbSteps dbSteps;

    @Before
    @Step("Подготовим данные для теста")
    public void prepare() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        dbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(CampaignsLogins.CLIENT);
    }

    @Test
    public void addStrategyToPayForInstallTest() {
        AddResponse response = api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withMobileAppCampaign(new MobileAppCampaignAddItemMap()
                                .withBiddingStrategy(new MobileAppCampaignStrategyAddMap()
                                        .withSearch(new MobileAppCampaignSearchStrategyAddMap()
                                                .withBiddingStrategyType(
                                                        MobileAppCampaignSearchStrategyTypeEnum.PAY_FOR_INSTALL)
                                                .withPayForInstall(new StrategyPayForInstallAddMap()
                                                        .withAverageCpi(averageCpi.bidLong().longValue())
                                                        .withWeeklySpendLimit(weekSpendLimit.bidLong().longValue())))
                                        .withNetwork(new MobileAppCampaignNetworkStrategyAddMap()
                                                .defaultServingOff())))),
                ExpectedResult.success());


        Long campaignId = response.getAddResults().get(0).getId();

        CampaignsRecord campaignsRecord = dbSteps.campaignsSteps().getCampaignById(campaignId);
        CampaignsRecord expectedCampaignsRecord = new CampaignsRecord();
        expectedCampaignsRecord.setCid(campaignId);
        expectedCampaignsRecord.setStrategyName(CampaignsStrategyName.autobudget_avg_cpi);
        expectedCampaignsRecord.setStrategyData(new StrategyData()
                .withSum(weekSpendLimit.doubleValue())
                .withName(CampaignsStrategyName.autobudget_avg_cpi)
                .withAvgCpi(averageCpi.doubleValue())
                .withPayForConversion(1)
                .withVersion(1)
                .toJsonElement());
        assertThat("стратегия правильно сохранилась в базе", campaignsRecord.intoMap(),
                beanDiffer(expectedCampaignsRecord.intoMap())
                        .useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()
                                .forFields(newPath("strategy_data/last_bidder_restart_time")).useMatcher(anything())));
    }
}
