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

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.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.StrategyPayForInstallMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
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
 */
@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@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 cpi = 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 Long campaignId;
    private DirectJooqDbSteps dbSteps;

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

    @Test
    public void updateStrategyToPayForInstallTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withMobileAppCampaign(new MobileAppCampaignUpdateItemMap()
                                .withBiddingStrategy(new MobileAppCampaignStrategyMap()
                                        .withSearch(new MobileAppCampaignSearchStrategyMap()
                                                .withBiddingStrategyType(
                                                        MobileAppCampaignSearchStrategyTypeEnum.PAY_FOR_INSTALL)
                                                .withPayForInstall(new StrategyPayForInstallMap()
                                                        .withWeeklySpendLimit(weekSpendLimit.bidLong().longValue())
                                                        .withAverageCpi(cpi.bidLong().longValue())))
                                        .withNetwork(new MobileAppCampaignNetworkStrategyMap().defaultServingOff())))),
                ExpectedResult.success());

        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(cpi.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())));
    }
}
