package ru.yandex.autotests.directapi.keywords.add;

import java.util.List;

import com.yandex.direct.api.v5.general.PriorityEnum;
import com.yandex.direct.api.v5.keywords.KeywordFieldEnum;
import com.yandex.direct.api.v5.keywords.KeywordGetItem;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PhrasesAdgroupType;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.darkside.model.CampaignsType;
import ru.yandex.autotests.directapi.keywords.KeywordsFeatures;
import ru.yandex.autotests.directapi.keywords.KeywordsLogins;
import ru.yandex.autotests.directapi.model.api5.Action;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
import ru.yandex.autotests.directapi.model.api5.keywords.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.keywords.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.keywords.KeywordAddMap;
import ru.yandex.autotests.directapi.model.api5.keywords.KeywordGetItemMap;
import ru.yandex.autotests.directapi.model.api5.keywords.KeywordsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static java.util.Collections.singletonList;
import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.hamcrest.Matchers.hasSize;
import static ru.yandex.autotests.directapi.matchers.beans.version5.BeanDifferMatcherV5.beanDifferV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Features(KeywordsFeatures.ADD)
@Issue("https://st.yandex-team.ru/DIRECT-83722")
public class AddKeywordsCpmBannerTest {

    private static final String CLIENT = KeywordsLogins.SINGLE_CLIENT_ADD;

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

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

    private static Long campaignId;
    private Long pid;
    private static DirectJooqDbSteps dbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(CLIENT);

    @BeforeClass
    public static void prepare() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignFakeSteps().setType(campaignId, CampaignsType.CPM_BANNER);
    }

    @Before
    public void initTest() {
        pid = api.userSteps.adGroupsSteps().addDefaultCpmBannerKeywordsAdGroup(campaignId);
    }

    @Test
    public void tryAddToCpmVideoAdGroup() {
        Long pid = api.userSteps.adGroupsSteps().addDefaultCpmBannerUserProfileAdGroup(campaignId);
        dbSteps.adGroupsSteps().setType(pid, PhrasesAdgroupType.cpm_video);
        api.userSteps.keywordsSteps().shouldGetResultOn(
                Action.ADD,
                new AddRequestMap().withKeywords(
                        new KeywordAddMap()
                                .defaultKeyword()
                                .withAdGroupId(pid)
                ),
                ExpectedResult.errors(
                        new Notification(6001, Api5ErrorDetails.FORBIDDEN_TO_CREATE_KEYWORDS_IN_GROUP_OF_THIS_TYPE))
        );
    }

    @Test
    public void addToCpmDealsCampaign() {
        Long campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignFakeSteps().setType(campaignId, CampaignsType.CPM_DEALS);
        Long pid = api.userSteps.adGroupsSteps().addDefaultCpmBannerKeywordsAdGroup(campaignId);
        api.userSteps.keywordsSteps().shouldGetResultOn(
                Action.ADD,
                new AddRequestMap().withKeywords(
                        new KeywordAddMap()
                                .defaultKeyword()
                                .withAdGroupId(pid)
                ),
                ExpectedResult.success()
        );
    }

    @Test
    public void tryAddAutotargeting() {
        api.userSteps.keywordsSteps().shouldGetResultOn(
                Action.ADD,
                new AddRequestMap().withKeywords(
                        new KeywordAddMap()
                                .shortAutotargeting(pid)
                ),
                ExpectedResult.errors(
                        new Notification(6001, Api5ErrorDetails.FORBIDDEN_TO_CREATE_KEYWORDS_IN_GROUP_OF_THIS_TYPE))
        );
    }

    @Test
    public void testDefaultBids() {
        long defaultBid = MoneyCurrency.get(Currency.RUB).getMinCpmPrice().bidLong().longValue();
        List<Long> keywordIds = api.userSteps.keywordsSteps().keywordsAdd(new KeywordAddMap()
                .defaultKeyword()
                .withAdGroupId(pid)
                .withBid(null)
                .withContextBid(null));
        assumeThat("было создано одно ключевое слово", keywordIds, hasSize(1));
        long keywordId = keywordIds.get(0);

        List<KeywordGetItem> response = api.userSteps.keywordsSteps().keywordsGet(new GetRequestMap()
                .withFieldNames(KeywordFieldEnum.BID, KeywordFieldEnum.CONTEXT_BID, KeywordFieldEnum.STRATEGY_PRIORITY)
                .withSelectionCriteria(new KeywordsSelectionCriteriaMap()
                        .withIds(keywordId)));

        assertThat("ставки по умолчанию установились верно", response, beanDifferV5(singletonList(
                new KeywordGetItemMap()
                        .withBid(defaultBid)
                        .withContextBid(defaultBid)
                        .withStrategyPriority(PriorityEnum.NORMAL).getBean())));
    }

    @Test
    public void testLessThanMinPrice() {
        api.userSteps.keywordsSteps().shouldGetResultOn(Action.ADD, new AddRequestMap().withKeywords(new KeywordAddMap()
                        .defaultKeyword()
                        .withAdGroupId(pid)
                        .withContextBid(MoneyCurrency.get(Currency.RUB).getMinCpmPrice().getPrevious().bidLong().longValue())),
                ExpectedResult.errors(new Notification(5005, Api5ErrorDetails.BID_VALUE_IN_FIELD_MUST_NOT_BE_LESS,
                        capitalize(KeywordAddMap.CONTEXT_BID),
                        MoneyCurrency.get(Currency.RUB).getNamePluralI(api.locale()),
                        MoneyCurrency.get(Currency.RUB).getMinCpmPrice().bidLong().longValue())));
    }

    @Test
    public void testMoreThanMaxPrice() {
        api.userSteps.keywordsSteps().shouldGetResultOn(Action.ADD, new AddRequestMap().withKeywords(new KeywordAddMap()
                        .defaultKeyword()
                        .withAdGroupId(pid)
                        .withContextBid(MoneyCurrency.get(Currency.RUB).getMaxCpmPrice().getNext().bidLong().longValue())),
                ExpectedResult.errors(new Notification(5005, Api5ErrorDetails.BID_VALUE_IN_FIELD_MUST_NOT_BE_MORE,
                        capitalize(KeywordAddMap.CONTEXT_BID),
                        MoneyCurrency.get(Currency.RUB).getNamePluralI(api.locale()),
                        MoneyCurrency.get(Currency.RUB).getMaxCpmPrice().bidLong().longValue())));
    }

    @Test
    public void tryAddKeywordToAdGroupWithUserProfile() {
        Long pid = api.userSteps.adGroupsSteps().addDefaultCpmBannerUserProfileAdGroup(campaignId);
        api.userSteps.keywordsSteps().shouldGetResultOn(
                Action.ADD,
                new AddRequestMap().withKeywords(
                        new KeywordAddMap()
                                .defaultKeyword()
                                .withAdGroupId(pid)
                ),
                ExpectedResult
                        .errors(new Notification(6001,
                                Api5ErrorDetails.FORBIDDEN_TO_CREATE_KEYWORDS_IN_GROUP_OF_THIS_TYPE)));
    }


}
