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

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

import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignSearchStrategyTypeEnum;
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.CampaignsSelectionCriteriaMap;
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.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionCrrAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyPayForConversionCrrMap;
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();
        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());
        }

        DynamicTextCampaignStrategyMap expectedStrategy = new DynamicTextCampaignStrategyMap()
                .withSearch(new DynamicTextCampaignSearchStrategyMap()
                        .withBiddingStrategyType(DynamicTextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_CRR)
                        .withPayForConversionCrr(new StrategyPayForConversionCrrMap()
                                .withGoalId(goalId)
                                .withCrr(crr)
                                .withWeeklySpendLimit(weeklySpendLimit)
                        )
                ).withNetwork(new DynamicTextCampaignNetworkStrategyMap().defaultServingOff());

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

        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()
                                                        .withWeeklySpendLimit(weeklySpendLimit)
                                                        .withCrr(crr)
                                                        .withGoalId(goalId)
                                                )
                                        ).withNetwork(new DynamicTextCampaignNetworkStrategyAddMap().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())
                        )
        );

        List<CampaignGetItem> campaignsFromApi = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(cid)
                )
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withDynamicTextCampaignFieldNames(DynamicTextCampaignFieldEnum.BIDDING_STRATEGY)
        );

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