package ru.yandex.autotests.direct.api.campaigns.add.textcampaign.strategy.payforconversioncrr;

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

import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
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 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.StrategyDataJava;
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.CampaignAddItemMap;
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.TextCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyMap;
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.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.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.anything;
import static ru.yandex.autotests.directapi.matchers.beans.version5.BeanDifferMatcherV5.beanDifferV5;
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;
import static ru.yandex.autotests.irt.testutils.beandiffer2.beanfield.BeanFieldPath.newPath;

@Aqua.Test
@Features(CampaignsFeatures.ADD)
@Description("Позитивные сценарии проверки создания тго со стратегией PayForConversionCrr")
@Tag(TagDictionary.TRUNK)
@RunWith(Parameterized.class)
public class StrategyPayForConversionCrrPositiveTest {

    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;
    private static final Integer COUNTER_ID = MetrikaGoals.getCounterForLogin(client);
    private static final Money MIN_LIMIT = MoneyCurrency.get(currency).getMinWeeklyBudgetAmount();
    private static final Money MAX_LIMIT = MoneyCurrency.get(currency).getMaxWeeklyBudgetAmount();

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(client);
    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();

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

    @Parameterized.Parameter(value = 0)
    public String description;

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

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

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

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection testData() {
        Object[][] data = new Object[][]{
                {
                        "Создание новой кампании",
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        DEFAULT_CRR,
                        DEFAULT_WEEKLY_SPEND_LIMIT,
                },
                {
                        "Создание новой кампании с минимальным ДРР",
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        MIN_CRR,
                        DEFAULT_WEEKLY_SPEND_LIMIT,
                },
                {
                        "Создание новой кампании с максимальным ДРР",
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        MAX_CRR,
                        DEFAULT_WEEKLY_SPEND_LIMIT,
                },
                {
                        "Создание новой кампании с минимальным бюджетом",
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        DEFAULT_CRR,
                        MIN_LIMIT.bidLong().longValue(),
                },
                {
                        "Создание новой кампании с максимальным бюджетом",
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        DEFAULT_CRR,
                        MAX_LIMIT.bidLong().longValue(),
                },
                {
                        "Создание новой кампании без недельного бюджета",
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        DEFAULT_CRR,
                        null
                }
        };
        return Arrays.asList(data);
    }

    private int shard;

    @Before
    public void setUp() {
        shard = api.userSteps.clientFakeSteps().getUserShard(client);
    }

    @Test
    public void shouldCreateFixCrrCampaign() {
        CampaignsRecord expectedDbRecord = new CampaignsRecord();
        TextCampaignStrategyMap expectedStrategy = new TextCampaignStrategyMap()
                .withSearch(new TextCampaignSearchStrategyMap()
                        .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_CRR)
                        .withPayForConversionCrr(new StrategyPayForConversionCrrMap()
                                .withGoalId(goalId)
                                .withCrr(crr)
                                .withWeeklySpendLimit(weeklySpendLimit)
                        )
                )
                .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff());

        StrategyDataJava expectedStrategyData = new StrategyDataJava()
                .withName(CampaignsStrategyName.autobudget_crr)
                .withGoalId(goalId)
                .withCrr(crr)
                .withPayForConversion(1)
                .withVersion(1);
        if (weeklySpendLimit != null) {
            expectedStrategyData.setSum(Money.valueOf(weeklySpendLimit).bidShort().doubleValue());
        }

        expectedDbRecord.setStrategyName(CampaignsStrategyName.autobudget_crr);
        expectedDbRecord.setStrategyData(expectedStrategyData.toJsonElement());

        long cid = api.userSteps.campaignSteps()
                .addCampaign(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withTextCampaign(new TextCampaignAddItemMap()
                                .withBiddingStrategy(new TextCampaignStrategyAddMap()
                                        .withSearch(new TextCampaignSearchStrategyAddMap()
                                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_CRR)
                                                .withPayForConversionCrr(new StrategyPayForConversionCrrAddMap()
                                                        .withGoalId(goalId)
                                                        .withCrr(crr)
                                                        .withWeeklySpendLimit(weeklySpendLimit)
                                                )
                                        )
                                        .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultServingOff())
                                )
                        )
                );


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

        assertThat("Кампания в БД со стратегией AUTOBUDGET_CRR и payForConversion = 1",
                campaignRecord.intoMap(),
                beanDiffer(expectedDbRecord.intoMap())
                        .useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()
                                .forFields(newPath("strategy_data/last_bidder_restart_time")).useMatcher(anything())
                        )
        );

        CampaignGetItem campaignFromApi = api.userSteps.campaignSteps().getCampaign(cid);

        assertThat("Получили корректную кампанию через API",
                campaignFromApi.getTextCampaign().getBiddingStrategy(),
                beanDifferV5(expectedStrategy.getBean())
        );
    }
}

