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

import java.sql.Timestamp;
import java.time.LocalDateTime;

import com.yandex.direct.api.v5.general.OperationEnum;
import org.hamcrest.Matchers;
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.enums.CampaignsStatusbssynced;
import ru.yandex.autotests.direct.db.steps.CampaignsSteps;
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.PriorityGoalsArrayMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.PriorityGoalsItemMap;
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.SmartCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SmartCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
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.hazelcast.SemaphoreRule;

import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.greaterThan;
import static ru.yandex.autotests.direct.api.campaigns.CampaignCommonMatchers.getMeaningfulGoalsJsonMatcher;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

@Aqua.Test
@Issue("https://st.yandex-team.ru/DIRECT-109983")
@Features(CampaignsFeatures.UPDATE)
@Description("Проверка обновления поля PriorityGoals. Позитивные сценарии")
public class UpdatePriorityGoalsDBValuesTest {

    private static String client = CampaignsLogins.UPDATE_CLIENT;
    private static final Integer COUNTER_ID = 34981090;
    private static final Long GOAL_ID = 17108070L;
    private static CampaignsSteps campaignJooqSteps;

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

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

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

    @BeforeClass
    public static void createCampaign() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        campaignJooqSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(client).campaignsSteps();
    }

    @Test
    public void updateWithEngagedSessionGoal() {
        Long cid = api.userSteps.campaignSteps().addDefaultSmartCampaign(client);

        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                        .withPriorityGoals(new PriorityGoalsUpdateItemMap()
                                                .withEngagedSessionGoalId()
                                                .withValue(1_000_000L)
                                                .withOperation(OperationEnum.SET)
                                        )
                                )
                        ),
                ExpectedResult.success());

        assertThat("meaningful_goals содержит правильный json",
                campaignJooqSteps.getCampOptionsById(cid).getMeaningfulGoals(),
                getMeaningfulGoalsJsonMatcher(PriorityGoalsItemMap.ENGAGED_SESSION_GOAL_ID, 1L));
    }

    @Test
    public void updateWithOldCounterGoal() {
        Long cid = api.userSteps.campaignSteps().addCampaign(new CampaignAddItemMap()
                .defaultCampaignAddItem()
                .withSmartCampaign(new SmartCampaignAddItemMap()
                        .withBiddingStrategy(new SmartCampaignStrategyAddMap()
                                .defaultSmartCampaignStrategy())
                        .withCounterId(Long.valueOf(COUNTER_ID))));


        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                        .withPriorityGoals(new PriorityGoalsUpdateItemMap()
                                                .withGoalId(GOAL_ID)
                                                .withValue(1_000_000L)
                                                .withOperation(OperationEnum.SET)
                                        )
                                )
                        ),
                ExpectedResult.success());

        assertThat("meaningful_goals содержит правильный json",
                campaignJooqSteps.getCampOptionsById(cid).getMeaningfulGoals(),
                getMeaningfulGoalsJsonMatcher(GOAL_ID, 1L));
    }

    @Test
    public void updateWithNewCounterGoal() {
        Long cid = api.userSteps.campaignSteps().addDefaultSmartCampaign(client);

        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                        .withCounterId(Long.valueOf(COUNTER_ID))
                                        .withPriorityGoals(new PriorityGoalsUpdateItemMap()
                                                .withGoalId(GOAL_ID)
                                                .withValue(1_000_000L)
                                                .withOperation(OperationEnum.SET)
                                        )
                                )
                        ),
                ExpectedResult.success());

        assertThat("meaningful_goals содержит правильный json",
                campaignJooqSteps.getCampOptionsById(cid).getMeaningfulGoals(),
                getMeaningfulGoalsJsonMatcher(GOAL_ID, 1L));
    }


    @Test
    public void updateWithEmptyGoals() {
        Long cid = api.userSteps.campaignSteps().addCampaign(new CampaignAddItemMap()
                .defaultCampaignAddItem()
                .withSmartCampaign(new SmartCampaignAddItemMap()
                        .withCounterId(Long.valueOf(COUNTER_ID))
                        .withBiddingStrategy(new SmartCampaignStrategyAddMap()
                                .defaultSmartCampaignStrategy())
                        .withPriorityGoals(new PriorityGoalsArrayMap()
                                .withItems(new PriorityGoalsItemMap()
                                        .withEngagedSessionGoalId()
                                        .withValue(1_000_000L))))
        );

        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                        .withPriorityGoals((PriorityGoalsUpdateSettingMap) null)
                                )
                        ),
                ExpectedResult.success());

        assertThat("meaningful_goals содержит правильный json",
                campaignJooqSteps.getCampOptionsById(cid).getMeaningfulGoals(),
                nullValue());
    }

    @Test
    public void updateWithChangedValue() {
        Long cid = api.userSteps.campaignSteps().addCampaign(new CampaignAddItemMap()
                .defaultCampaignAddItem()
                .withSmartCampaign(new SmartCampaignAddItemMap()
                        .withCounterId(Long.valueOf(COUNTER_ID))
                        .withBiddingStrategy(new SmartCampaignStrategyAddMap()
                                .defaultSmartCampaignStrategy())
                        .withPriorityGoals(new PriorityGoalsArrayMap()
                                .withItems(new PriorityGoalsItemMap()
                                        .withEngagedSessionGoalId()
                                        .withValue(1_000_000L))))
        );

        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                        .withPriorityGoals(new PriorityGoalsUpdateItemMap()
                                                .withEngagedSessionGoalId()
                                                .withValue(2_000_000L)
                                                .withOperation(OperationEnum.SET)
                                        )
                                )
                        ),
                ExpectedResult.success());

        assertThat("meaningful_goals содержит правильный json",
                campaignJooqSteps.getCampOptionsById(cid).getMeaningfulGoals(),
                getMeaningfulGoalsJsonMatcher(PriorityGoalsItemMap.ENGAGED_SESSION_GOAL_ID, 2L));

    }

    @Test
    public void updateCheckStatusBsSynced() {
        Long cid = api.userSteps.campaignSteps().addDefaultSmartCampaign(client);

        campaignJooqSteps.setCampaignsStatusBsSynced(cid, CampaignsStatusbssynced.Yes);

        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                        .withPriorityGoals(new PriorityGoalsUpdateItemMap()
                                                .withEngagedSessionGoalId()
                                                .withValue(1_000_000L)
                                                .withOperation(OperationEnum.SET)
                                        )
                                )
                        ),
                ExpectedResult.success());

        assertThat("у кампании сбросился StatusBsSynced",
                campaignJooqSteps.getCampaignById(cid).getStatusbssynced(),
                Matchers.equalTo(CampaignsStatusbssynced.No));
    }

    @Test
    public void updateCheckLastChange() {
        Long cid = api.userSteps.campaignSteps().addDefaultSmartCampaign(client);

        Timestamp lastChange = Timestamp.valueOf(LocalDateTime.now().minusDays(5).withNano(0));
        campaignJooqSteps.setCampaignsLastChange(cid, lastChange);

        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withSmartCampaign(new SmartCampaignUpdateItemMap()
                                        .withPriorityGoals(new PriorityGoalsUpdateItemMap()
                                                .withEngagedSessionGoalId()
                                                .withValue(1_000_000L)
                                                .withOperation(OperationEnum.SET)
                                        )
                                )
                        ),
                ExpectedResult.success());

        assertThat("LastChange у кампании изменился",
                campaignJooqSteps.getCampaignById(cid).getLastchange().toLocalDateTime(),
                greaterThan(lastChange.toLocalDateTime()));
    }
}
