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.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.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.Money;
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.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.StrategyAverageCrrAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCrrMap;
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.Tag;
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.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@Description("Сценарии смены типа стратегий с/на PayForConversionCrr для до")
@Tag(TagDictionary.TRUNK)
@RunWith(Parameterized.class)
public class StrategyPayForConversionCrrChangeStrategyTest {

    private static final String CLIENT = CampaignsLogins.CLIENT;
    private static final Integer COUNTER_ID = MetrikaGoals.getCounterForLogin(CLIENT);

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

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

    private int shard;

    @Parameterized.Parameter(value = 0)
    public String description;
    @Parameterized.Parameter(value = 1)
    public DynamicTextCampaignSearchStrategyAddMap addData;
    @Parameterized.Parameter(value = 2)
    public DynamicTextCampaignSearchStrategyMap updateData;
    @Parameterized.Parameter(value = 3)
    public CampaignsStrategyName expectedStrategyNameInDb;
    @Parameterized.Parameter(value = 4)
    public StrategyData expectedStrategyDataInDb;

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection testData() {
        Object[][] data = {
                {
                        "Обновление дефолтной стратегии на PayForConversionCrr",
                        new DynamicTextCampaignSearchStrategyAddMap().defaultHighestPosition(),
                        new DynamicTextCampaignSearchStrategyMap()
                                .withBiddingStrategyType(DynamicTextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_CRR)
                                .withPayForConversionCrr(new StrategyPayForConversionCrrMap()
                                .withGoalId(MetrikaGoals.getGoalForCounter(COUNTER_ID))
                                .withCrr(DEFAULT_CRR)
                                .withWeeklySpendLimit(DEFAULT_WEEKLY_SPEND_LIMIT)
                        ),
                        CampaignsStrategyName.autobudget_crr,
                        new StrategyData()
                                .withName(CampaignsStrategyName.autobudget_crr)
                                .withGoalId(MetrikaGoals.getGoalForCounter(COUNTER_ID).toString())
                                .withSum(Money.valueOf(DEFAULT_WEEKLY_SPEND_LIMIT).bidShort().doubleValue())
                                .withCrr(DEFAULT_CRR)
                                .withPayForConversion(1)
                                .withVersion(1)
                },
                {
                        "Обновление стратегии AverageCrr на PayForConversionCrr",
                        new DynamicTextCampaignSearchStrategyAddMap()
                                .withBiddingStrategyType(DynamicTextCampaignSearchStrategyTypeEnum.AVERAGE_CRR)
                                .withAverageCrr(new StrategyAverageCrrAddMap()
                                .withGoalId(MetrikaGoals.getGoalForCounter(COUNTER_ID))
                                .withCrr(DEFAULT_CRR)
                        ),
                        new DynamicTextCampaignSearchStrategyMap()
                                .withBiddingStrategyType(DynamicTextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_CRR)
                                .withPayForConversionCrr(new StrategyPayForConversionCrrMap()
                                .withGoalId(MetrikaGoals.getGoalForCounter(COUNTER_ID))
                                .withCrr(DEFAULT_CRR)
                                .withWeeklySpendLimit(DEFAULT_WEEKLY_SPEND_LIMIT)
                        ),
                        CampaignsStrategyName.autobudget_crr,
                        new StrategyData()
                                .withName(CampaignsStrategyName.autobudget_crr)
                                .withGoalId(MetrikaGoals.getGoalForCounter(COUNTER_ID).toString())
                                .withSum(Money.valueOf(DEFAULT_WEEKLY_SPEND_LIMIT).bidShort().doubleValue())
                                .withCrr(DEFAULT_CRR)
                                .withPayForConversion(1)
                                .withVersion(1)

                },
                {
                        "Обновление стратегии PayForConversionCrr на AverageCrr",
                        new DynamicTextCampaignSearchStrategyAddMap()
                                .withBiddingStrategyType(DynamicTextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_CRR)
                                .withPayForConversionCrr(new StrategyPayForConversionCrrAddMap()
                                .withGoalId(MetrikaGoals.getGoalForCounter(COUNTER_ID))
                                .withCrr(DEFAULT_CRR)
                        ),
                        new DynamicTextCampaignSearchStrategyMap()
                                .withBiddingStrategyType(DynamicTextCampaignSearchStrategyTypeEnum.AVERAGE_CRR)
                                .withAverageCrr(new StrategyAverageCrrMap()
                                .withGoalId(MetrikaGoals.getGoalForCounter(COUNTER_ID))
                                .withCrr(DEFAULT_CRR)
                                .withWeeklySpendLimit(DEFAULT_WEEKLY_SPEND_LIMIT)
                        ),
                        CampaignsStrategyName.autobudget_crr,
                        new StrategyData()
                                .withName(CampaignsStrategyName.autobudget_crr)
                                .withGoalId(MetrikaGoals.getGoalForCounter(COUNTER_ID).toString())
                                .withSum(Money.valueOf(DEFAULT_WEEKLY_SPEND_LIMIT).bidShort().doubleValue())
                                .withCrr(DEFAULT_CRR)
                                .withPayForConversion(0)
                                .withVersion(1)
                },
                {
                        "Обновление стратегии PayForConversionCrr на дефолтную",
                        new DynamicTextCampaignSearchStrategyAddMap()
                                .withBiddingStrategyType(DynamicTextCampaignSearchStrategyTypeEnum.PAY_FOR_CONVERSION_CRR)
                                .withPayForConversionCrr(new StrategyPayForConversionCrrAddMap()
                                .withGoalId(MetrikaGoals.getGoalForCounter(COUNTER_ID))
                                .withCrr(DEFAULT_CRR)
                        ),
                        new DynamicTextCampaignSearchStrategyMap().defaultHighestPosition(),
                        CampaignsStrategyName.default_,
                        new StrategyData()
                                .withName(CampaignsStrategyName.default_)
                                .withVersion(1)
                }
        };

        return Arrays.asList(data);
    }

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

    @Test
    public void shouldUpdateCampaign() {
        long cid = api.userSteps.campaignSteps().addCampaign(new CampaignAddItemMap()
                .defaultCampaignAddItem()
                .withDynamicTextCampaign(new DynamicTextCampaignAddItemMap()
                        .withBiddingStrategy(new DynamicTextCampaignStrategyAddMap()
                                .withSearch(addData)
                                .withNetwork(new DynamicTextCampaignNetworkStrategyAddMap().defaultServingOff())
                        )
                )
        );

        CampaignsRecord expectedDbRecord = new CampaignsRecord();
        expectedDbRecord.setStrategyName(expectedStrategyNameInDb);
        expectedDbRecord.setStrategyData(expectedStrategyDataInDb.toJsonElement());
        expectedDbRecord.setCid(cid);

        api.userSteps.campaignSteps()
                .shouldGetResultOnUpdate(new UpdateRequestMap()
                                .withCampaigns(new CampaignUpdateItemMap()
                                        .withId(cid)
                                        .withDynamicTextCampaign(new DynamicTextCampaignUpdateItemMap()
                                                .withBiddingStrategy(new DynamicTextCampaignStrategyMap()
                                                        .withSearch(updateData)
                                                        .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)
        );
    }
}
