package ru.yandex.autotests.direct.api.campaigns.update.dynamictextcampaign.strategy.payforconversioncrr;

import java.util.Arrays;
import java.util.Collection;

import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignSearchStrategyTypeEnum;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

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.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionCrrAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionCrrMap;
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.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static ru.yandex.autotests.direct.api.campaigns.CampaignCommonMatchers.strategyDataCompareStrategy;
import static ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionCrrAddMap.DEFAULT_CRR;
import static ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionCrrAddMap.DEFAULT_WEEKLY_SPEND_LIMIT;
import static ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionCrrAddMap.MAX_CRR;
import static ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionCrrAddMap.MIN_CRR;
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)
@RunWith(Parameterized.class)
@Description("Сценарии проверки редактирования до со стратегией PayForConversionCrr")
public class StrategyPayForConversionCrrPositiveTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Integer COUNTER_ID = MetrikaGoals.getCounterForLogin(client);
    private static final Money MIN_LIMIT = MoneyCurrency.get(Currency.RUB).getMinWeeklyBudgetAmount();
    private static final Money MAX_LIMIT = MoneyCurrency.get(Currency.RUB).getMaxWeeklyBudgetAmount();

    @ClassRule
    public static final ApiSteps api = new ApiSteps().as(client);

    @ClassRule
    public static final SemaphoreRule semaphore = Semaphore.getSemaphore();

    @Rule
    public Trashman trasher = new Trashman(api);

    @Parameterized.Parameter(value = 0)
    public Integer crr;

    @Parameterized.Parameter(value = 1)
    public Long goalId;

    @Parameterized.Parameter(value = 2)
    public Long weeklySpendLimit;

    @Parameterized.Parameters(name = "crr = {0}, goalId = {1}, weeklySpendLimit = {2}")
    public static Collection strategies() {
        Object[][] data = new Object[][] {
                // CRR
                {
                        MIN_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        DEFAULT_WEEKLY_SPEND_LIMIT,
                },
                {
                        MAX_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        DEFAULT_WEEKLY_SPEND_LIMIT,
                },
                // SUM
                {
                        DEFAULT_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        MIN_LIMIT.bidLong().longValue(),
                },
                {
                        DEFAULT_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        MAX_LIMIT.bidLong().longValue(),
                },
                {
                        DEFAULT_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        null,
                }
        };
        return Arrays.asList(data);
    }

    @Test
    public void shouldUpdateCampaignFields() {
        int shard = api.userSteps.clientFakeSteps().getUserShard(client);
        long cid = api.userSteps.campaignSteps().addCampaign(new CampaignAddItemMap()
                .defaultCampaignAddItem()
                .withDynamicTextCampaign(new DynamicTextCampaignAddItemMap()
                        .withBiddingStrategy(new DynamicTextCampaignStrategyAddMap()
                                .withSearch(new DynamicTextCampaignSearchStrategyAddMap()
                                        .withBiddingStrategyType(DynamicTextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_CRR)
                                        .withPayForConversionCrr(new StrategyPayForConversionCrrAddMap()
                                                .withGoalId(goalId)
                                                .withCrr(DEFAULT_CRR)
                                                .withWeeklySpendLimit(DEFAULT_WEEKLY_SPEND_LIMIT)
                                        )
                                )
                                .withNetwork(new DynamicTextCampaignNetworkStrategyAddMap().defaultServingOff())
                        )
                )
        );

        CampaignsRecord expectedDbRecord = new CampaignsRecord();
        expectedDbRecord.setStrategyName(CampaignsStrategyName.autobudget_crr);
        expectedDbRecord.setStrategyData(new StrategyData()
                .withName(CampaignsStrategyName.autobudget_crr)
                .withCrr(crr)
                .withGoalId(goalId.toString())
                .withSum(weeklySpendLimit == null ? null : Money.valueOf(weeklySpendLimit).bidShort().doubleValue())
                .withPayForConversion(1)
                .withVersion(1)
                .toJsonElement()
        );
        expectedDbRecord.setCid(cid);

        api.userSteps.campaignSteps()
                .shouldGetResultOnUpdate(new UpdateRequestMap()
                                .withCampaigns(new CampaignUpdateItemMap()
                                        .withId(cid)
                                        .withDynamicTextCampaign(new DynamicTextCampaignUpdateItemMap()
                                                .withBiddingStrategy(new DynamicTextCampaignStrategyMap()
                                                        .withSearch(new DynamicTextCampaignSearchStrategyMap()
                                                                .withBiddingStrategyType(DynamicTextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_CRR)
                                                                .withPayForConversionCrr(new StrategyPayForConversionCrrMap()
                                                                        .withCrr(crr)
                                                                        .withGoalId(goalId)
                                                                        .withWeeklySpendLimit(weeklySpendLimit)
                                                                )
                                                        )
                                                        .withNetwork(new DynamicTextCampaignNetworkStrategyMap().defaultServingOff())
                                                )
                                        )
                                ),
                        ExpectedResult.success()
                );

        CampaignsRecord campaignRecord =
                api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps().getCampaignById(cid);

        assertThat("Кампания в БД со стратегией AUTOBUDGET_CRR и payForConversion = 1",
                campaignRecord.intoMap(),
                beanDiffer(expectedDbRecord.intoMap())
                        .useCompareStrategy(strategyDataCompareStrategy)
        );
    }
}
