package ru.yandex.autotests.direct.api.campaigns.update;

import java.util.List;

import com.yandex.direct.api.v5.campaigns.DailyBudgetModeEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignSettingsEnum;
import com.yandex.direct.api.v5.general.OperationEnum;
import com.yandex.direct.api.v5.general.YesNoEnum;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.BeforeClass;
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.models.jooq.ppc.tables.records.CampOptionsRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampaignsRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.MetrikaCountersRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.StrategiesRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.StrategyMetrikaCountersRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.money.Currency;
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.DailyBudgetMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.PriorityGoalsUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.PriorityGoalsUpdateSettingMap;
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.TextCampaignSettingMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ArrayOfIntegerMap;
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.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.CoreMatchers.nullValue;
import static ru.yandex.autotests.direct.api.campaigns.CampaignCommonMatchers.compareCampaignAndStrategy;
import static ru.yandex.autotests.direct.api.campaigns.CampaignCommonMatchers.getMeaningfulGoalsJsonMatcher;

@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@Description("Проверка сохранения в базу пакетных стратегий при обновлении кампании")
@Issue("https://st.yandex-team.ru/DIRECT-160676")
public class UpdatePackageStrategiesTest {

    private static final String CLIENT = CampaignsLogins.CLIENT_NEW_FEATURES;
    private static final Integer COUNTER_ID = 62927671;
    private static final Long GOAL_ID = 104567458L;

    private static Long clientId;
    private static DirectJooqDbSteps jooqDbSteps;

    private Long cid;

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

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

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

    @BeforeClass
    @Step("Подготовим данные для теста")
    public static void beforeClass() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);
        int shard = api.userSteps.clientFakeSteps().getUserShard(CLIENT);
        jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);
        clientId = jooqDbSteps.shardingSteps().getClientIdByLogin(CLIENT);
    }

    @Before
    @Step("Подготовим данные для теста")
    public void before() {
        cid = api.userSteps.campaignSteps().addCampaign(new CampaignAddItemMap()
                .defaultCampaignAddItem()
                .withTextCampaign(new TextCampaignAddItemMap()
                        .withBiddingStrategy(new TextCampaignStrategyAddMap()
                                .withSearch(new TextCampaignSearchStrategyAddMap().defaultAverageCpc(Currency.RUB))
                                .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultNetworkDefault()))
                        .withCounterIds(COUNTER_ID)));
    }

    @Test
    public void defaultStrategyTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withTextCampaign(new TextCampaignUpdateItemMap()
                                        .withBiddingStrategy(new TextCampaignStrategyMap()
                                                .withSearch(new TextCampaignSearchStrategyMap().defaultHighestPosition())
                                                .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff())))),
                ExpectedResult.success(cid));
        compareStrategyAndCampaign(nullValue(String.class));
    }

    @Test
    public void notDefaultStrategyTest() {
        Long dayBudget = 1000_000_000L;
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withDailyBudget(new DailyBudgetMap()
                                        .withAmount(dayBudget)
                                        .withMode(DailyBudgetModeEnum.STANDARD))
                                .withTextCampaign(new TextCampaignUpdateItemMap()
                                        .withBiddingStrategy(new TextCampaignStrategyMap()
                                                .withSearch(new TextCampaignSearchStrategyMap().defaultServingOff())
                                                .withNetwork(new TextCampaignNetworkStrategyMap().defaultMaximumCoverage()))
                                        .withSettings(new TextCampaignSettingMap()
                                                .withOption(TextCampaignSettingsEnum.MAINTAIN_NETWORK_CPC)
                                                .withValue(YesNoEnum.NO)))),
                ExpectedResult.success(cid));
        compareStrategyAndCampaign(nullValue(String.class));
    }

    @Test
    public void meaningfulGoalsTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withTextCampaign(new TextCampaignUpdateItemMap()
                                        .withBiddingStrategy(new TextCampaignStrategyMap()
                                                .withSearch(new TextCampaignSearchStrategyMap().defaultHighestPosition())
                                                .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff()))
                                        .withCounterIds(COUNTER_ID)
                                        .withPriorityGoals(new PriorityGoalsUpdateSettingMap()
                                                .withItems(new PriorityGoalsUpdateItemMap()
                                                        .withGoalId(GOAL_ID)
                                                        .withValue(1_000_000L)
                                                        .withOperation(OperationEnum.SET))))),
                ExpectedResult.success(cid));
        compareStrategyAndCampaign(getMeaningfulGoalsJsonMatcher(GOAL_ID, 1L));
    }

    @Test
    public void strategyMetrikaCountersWithoutChangesTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withTextCampaign(new TextCampaignUpdateItemMap()
                                        .withBiddingStrategy(new TextCampaignStrategyMap()
                                                .withSearch(new TextCampaignSearchStrategyMap().defaultHighestPosition())
                                                .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff())))),
                ExpectedResult.success(cid));
        compareStrategyAndCampaign(nullValue(String.class));
    }

    @Test
    public void strategyMetrikaCountersDeleteTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withTextCampaign(new TextCampaignUpdateItemMap()
                                        .withBiddingStrategy(new TextCampaignStrategyMap()
                                                .withSearch(new TextCampaignSearchStrategyMap().defaultHighestPosition())
                                                .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff()))
                                        .withCounterIds((ArrayOfIntegerMap) null))),
                ExpectedResult.success(cid));
        compareStrategyAndCampaign(nullValue(String.class));
    }

    @Test
    public void strategyMetrikaCountersReplaceTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withTextCampaign(new TextCampaignUpdateItemMap()
                                        .withBiddingStrategy(new TextCampaignStrategyMap()
                                                .withSearch(new TextCampaignSearchStrategyMap().defaultHighestPosition())
                                                .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff()))
                                        .withCounterIds(COUNTER_ID + 1))),
                ExpectedResult.success(cid));
        compareStrategyAndCampaign(nullValue(String.class));
    }

    private void compareStrategyAndCampaign(Matcher<String> meaningfulGoalsMatcher) {
        CampaignsRecord campaignsRecord = jooqDbSteps.campaignsSteps().getCampaignById(cid);
        CampOptionsRecord campOptionsRecord = jooqDbSteps.campaignsSteps().getCampOptionsById(cid);
        Long strategyId = campaignsRecord.getStrategyId();
        StrategiesRecord strategiesRecord = jooqDbSteps.strategiesSteps().getStrategiesRecord(strategyId);
        List<MetrikaCountersRecord> campaignMetrikaCounters =
                jooqDbSteps.metrikaCountersSteps().getAllMetrikaCountersByCid(cid);
        List<StrategyMetrikaCountersRecord> strategyMetrikaCounters =
                jooqDbSteps.strategyMetrikaCountersSteps().getStrategyMetrikaCountersRecords(strategyId);
        compareCampaignAndStrategy(campaignsRecord, campOptionsRecord, campaignMetrikaCounters, strategiesRecord,
                strategyMetrikaCounters, meaningfulGoalsMatcher, false, null);
    }
}
