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

import java.util.List;
import java.util.stream.Collectors;

import com.yandex.direct.api.v5.retargetinglists.RetargetingListFieldEnum;
import com.yandex.direct.api.v5.retargetinglists.RetargetingListGetItem;
import com.yandex.direct.api.v5.retargetinglists.RetargetingListRuleOperatorEnum;
import org.apache.commons.lang.RandomStringUtils;
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.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5Error;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetailsJava;
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.retargetinglists.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListAddItemMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListRuleArgumentItemMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListRuleItemMap;
import ru.yandex.autotests.directapi.model.retargeting.RetargetingGoalType;
import ru.yandex.autotests.directapi.retargetinglists.RetargetingListsFeatures;
import ru.yandex.autotests.directapi.retargetinglists.RetargetingListsLogins;
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.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static ru.yandex.autotests.directapi.apiclient.errors.Path.path;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * https://st.yandex-team.ru/TESTIRT-8519
 */
@Aqua.Test
@Features(RetargetingListsFeatures.ADD)
@Description("Проверка списания баллов API")
@Issue("https://st.yandex-team.ru/DIRECT-48447")
public class AddRetargetingListsUnitsTest {
    private static final int ADD_COST = 10;
    private static final int ITEM_COST_ON_ADD = 2;
    private static final int GENERAL_FAULT_COST = 50;
    private static final int ERROR_COST = 20;
    private static Long correctGoalId1;
    private static Long correctGoalId2;
    private static final String LOGIN = RetargetingListsLogins.LOGIN_RETARGETING35;

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

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

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

    @BeforeClass
    public static void prepare() {
        List<Long> goalIds =
                api.userSteps.retargetingSteps().getRetargetingGoalIDsByType(LOGIN, RetargetingGoalType.GOAL);
        assumeThat("у клиента должно быть > 1 цели", goalIds.size(), greaterThan(1));
        correctGoalId1 = goalIds.get(0);
        correctGoalId2 = goalIds.get(1);
    }

    @Before
    public void init() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        List<RetargetingListGetItem> listsGetItems = api.userSteps.retargetingListsSteps().get(
                new GetRequestMap()
                        .withFieldNames(
                                RetargetingListFieldEnum.ID
                        ));
        api.userSteps.retargetingListsSteps().deleteByIds(
                LOGIN, listsGetItems.stream().map(RetargetingListGetItem::getId).collect(Collectors.toList())
        );
    }

    @Test
    public void addSuccess() {
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        api.userSteps.retargetingListsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withRetargetingLists(
                                new RetargetingListAddItemMap()
                                        .defaultRetargetingListAddItemMap(new RetargetingListRuleArgumentItemMap()
                                                .withMembershipLifeSpan(
                                                        RetargetingListRuleArgumentItemMap.DEFAULT_MEMBERSHIP_LIFE_SPAN
                                                )
                                                .withExternalId(correctGoalId2))),
                ExpectedResult.success());
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        assertThat("стоимость добавления одного объекта",
                unitsBefore - unitsAfter, equalTo(ADD_COST + ITEM_COST_ON_ADD));
    }

    @Test
    public void addSomeRetargetingLists() {
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        api.userSteps.retargetingListsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withRetargetingLists(
                                new RetargetingListAddItemMap()
                                        .defaultRetargetingListAddItemMap(new RetargetingListRuleArgumentItemMap()
                                                .withMembershipLifeSpan(
                                                        RetargetingListRuleArgumentItemMap.DEFAULT_MEMBERSHIP_LIFE_SPAN
                                                )
                                                .withExternalId(correctGoalId1)),

                                new RetargetingListAddItemMap()
                                        .defaultRetargetingListAddItemMap(new RetargetingListRuleArgumentItemMap()
                                                .withMembershipLifeSpan(
                                                        RetargetingListRuleArgumentItemMap.DEFAULT_MEMBERSHIP_LIFE_SPAN
                                                )
                                                .withExternalId(correctGoalId2))),
                ExpectedResult.success(), ExpectedResult.success());
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        assertThat("стоимость добавления двух объектов",
                unitsBefore - unitsAfter, equalTo(ADD_COST + ITEM_COST_ON_ADD * 2));
    }

    @Test
    public void addOneInvalidRetargetingLists() {
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        api.userSteps.retargetingListsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withRetargetingLists(
                                new RetargetingListAddItemMap()
                                        .withRandomName()
                                        .withRandomDescription()
                                        .withRules(new RetargetingListRuleItemMap()
                                                .withOperator(RetargetingListRuleOperatorEnum.ANY)
                                                .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                        .withMembershipLifeSpan(
                                                                RetargetingListRuleArgumentItemMap.DEFAULT_MEMBERSHIP_LIFE_SPAN)))),
                ExpectedResult.errors(
                        new Notification(5005,
                                Api5ErrorDetailsJava.FIELD_MUST_BE_POSITIVE_INTEGER,
                                path(RetargetingListAddItemMap.RULES,
                                        0,
                                        RetargetingListRuleItemMap.ARGUMENTS,
                                        0,
                                        RetargetingListRuleArgumentItemMap.EXTERNAL_ID)
                        )));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        int actualCost = unitsBefore - unitsAfter;
        int expectedCost = ADD_COST + ERROR_COST;
        assertThat("списалось верное число баллов", actualCost, equalTo(expectedCost));
    }

    @Test
    public void addTwoInvalidRetargetingLists() {
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        api.userSteps.retargetingListsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withRetargetingLists(
                                new RetargetingListAddItemMap()
                                        .withName("Name " + RandomStringUtils.randomAlphanumeric(5))
                                        .withDescription("Description " + RandomStringUtils.randomAlphanumeric(5))
                                        .withRules(new RetargetingListRuleItemMap()
                                                .withOperator(RetargetingListRuleOperatorEnum.ALL)
                                                .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                        .withExternalId(correctGoalId1))),
                                new RetargetingListAddItemMap()
                                        .withName("Name " + RandomStringUtils.randomAlphanumeric(5))
                                        .withDescription("Description " + RandomStringUtils.randomAlphanumeric(5))
                                        .withRules(new RetargetingListRuleItemMap()
                                                .withOperator(RetargetingListRuleOperatorEnum.NONE)
                                                .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                        .withMembershipLifeSpan(35)
                                                        .withExternalId(-1)))),
                ExpectedResult.errors(new Notification(5000,
                        Api5ErrorDetailsJava.MEMBERSHIP_LIFESPAN_MUST_BE_SET_FOR_GOAL_AND_SEGMENT,
                        path(RetargetingListAddItemMap.RULES,
                                0,
                                RetargetingListRuleItemMap.ARGUMENTS,
                                0))),
                ExpectedResult.errors(new Notification(5005,
                        Api5ErrorDetailsJava.FIELD_MUST_BE_POSITIVE_INTEGER,
                        path(RetargetingListAddItemMap.RULES,
                                0,
                                RetargetingListRuleItemMap.ARGUMENTS,
                                0,
                                RetargetingListRuleArgumentItemMap.EXTERNAL_ID)
                )));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        int actualCost = unitsBefore - unitsAfter;
        int expectedCost = ADD_COST + ERROR_COST * 2;
        assertThat("списалось верное число баллов", actualCost, equalTo(expectedCost));
    }

    @Test
    public void addOneValidAndOneInvalidRetargetingLists() {
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        api.userSteps.retargetingListsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withRetargetingLists(
                                new RetargetingListAddItemMap()
                                        .withName("Name " + RandomStringUtils.randomAlphanumeric(5))
                                        .withDescription("Description " + RandomStringUtils.randomAlphanumeric(5))
                                        .withRules(new RetargetingListRuleItemMap()
                                                .withOperator(RetargetingListRuleOperatorEnum.ANY)
                                                .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                        .withRandomMembershipLifeSpan()
                                                        .withExternalId(correctGoalId1))),

                                new RetargetingListAddItemMap()
                                        .withName("Name " + RandomStringUtils.randomAlphanumeric(5))
                                        .withDescription("Description " + RandomStringUtils.randomAlphanumeric(5))
                                        .withRules(new RetargetingListRuleItemMap()
                                                .withOperator(RetargetingListRuleOperatorEnum.ALL)
                                                .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                        .withExternalId(correctGoalId2)))),
                ExpectedResult.success(),
                ExpectedResult.errors(new Notification(5000,
                        Api5ErrorDetailsJava.MEMBERSHIP_LIFESPAN_MUST_BE_SET_FOR_GOAL_AND_SEGMENT,
                        path(RetargetingListAddItemMap.RULES,
                                0,
                                RetargetingListRuleItemMap.ARGUMENTS,
                                0))));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        int actualCost = unitsBefore - unitsAfter;
        int expectedCost = ADD_COST + ERROR_COST + ITEM_COST_ON_ADD;
        assertThat("списалось верное число баллов", actualCost, equalTo(expectedCost));
    }

    @Test
    public void generalErrorOnAddRetargetingLists() {
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        api.userSteps.retargetingListsSteps().expectErrorOnAdd(new AddRequestMap()
                        .withRetargetingLists(
                                new RetargetingListAddItemMap()
                                        .withRandomName()
                                        .withRandomDescription()
                                        .withRules(new RetargetingListRuleItemMap()
                                                .withOperator(RetargetingListRuleOperatorEnum.ANY))),
                new Api5Error(8000, Api5ErrorDetailsJava.IN_ELEMENT_OF_ARRAY_MISSING_REQUIRED_FIELD,
                        path(AddRequestMap.RETARGETING_LISTS,
                                RetargetingListAddItemMap.RULES),
                        path(RetargetingListRuleItemMap.ARGUMENTS)));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        assertThat("списалось верное кол-во баллов", unitsBefore - unitsAfter, equalTo(GENERAL_FAULT_COST));
    }

    @Test
    public void notEnoughUnitsOnAddRetargetingLists() {
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        api.userSteps.clientFakeSteps().fakeWithdrawClientUnits(LOGIN, unitsBefore);
        unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        assumeThat("доступные баллы пользователя", unitsBefore, equalTo(0));

        api.userSteps.retargetingListsSteps().expectErrorOnAdd(new AddRequestMap()
                        .withRetargetingLists(
                                new RetargetingListAddItemMap()
                                        .withRandomName()
                                        .withRandomDescription()
                                        .withRules(new RetargetingListRuleItemMap()
                                                .withOperator(RetargetingListRuleOperatorEnum.ANY)
                                                .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                        .withMembershipLifeSpan(
                                                                RetargetingListRuleArgumentItemMap.DEFAULT_MEMBERSHIP_LIFE_SPAN)))),
                new Api5Error(152, Api5ErrorDetailsJava.NOT_ENOUGH_UNITS));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        assertThat("доступные баллы пользователя после ошибки", unitsAfter, equalTo(0));
    }
}
