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

import com.yandex.direct.api.v5.retargetinglists.RetargetingListRuleOperatorEnum;
import com.yandex.direct.api.v5.retargetinglists.RetargetingListTypeEnum;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.junit.BeforeClass;
import org.junit.ClassRule;
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.Api5ErrorDetailsJava;
import ru.yandex.autotests.directapi.darkside.model.CampaignsType;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.PixelProvider;
import ru.yandex.autotests.directapi.model.User;
import ru.yandex.autotests.directapi.model.api5.ads.AdAddItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.CpmBannerAdBuilderAdAddMap;
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.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.api5.retargetinglists.RetargetingListUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.UpdateRequestMap;
import ru.yandex.autotests.directapi.retargetinglists.RetargetingListsFeatures;
import ru.yandex.autotests.directapi.retargetinglists.RetargetingListsLogins;
import ru.yandex.autotests.directapi.rules.ApiSteps;
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 java.util.Collections.singletonList;
import static ru.yandex.autotests.directapi.model.AdfoxDealPlacement.getPlacementJsonsFromPageIds;

@Aqua.Test
@Features(RetargetingListsFeatures.UPDATE)
@Description("Проверка валидации при обновлении ретаргетингов, зависящей от cpm-баннеров на связанных группах объвялений")
@Issue("DIRECT-83722")
public class UpdateRetargetingListsCpmAdGroupTest {
    private static String agency = Logins.AGENCY_ANOTHER;

    private static final String CLIENT_LOGIN = RetargetingListsLogins.ADD_SUBCLIENT2;
    private static final String AGENCY_LOGIN = RetargetingListsLogins.ADD_AGENCY_REP;
    private static final Long PUBLIC_GOAL_ID = 2499000002L;
    private static final Long PRIVATE_GOAL_ID = 2499000010L;
    public static final Long MIN_TEST_DEAL_ID = 2000000L;
    public static final Long MAX_TEST_DEAL_ID = 10000000L;
    public static final Long BIG_PLACEMENT_PAGE_ID = 63545376L;

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

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

    private static Long creativeIdForCpmBanners;
    private static Integer membershipLifeSpan;
    private static Long cpmAdGroupId;
    private static Long retargetingListId;


    @BeforeClass
    public static void prepare() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(AGENCY_LOGIN);
        membershipLifeSpan = RandomUtils.nextInt(1, 90);

        creativeIdForCpmBanners =
                api.userSteps.getDirectJooqDbSteps().useShardForLogin(CLIENT_LOGIN).perfCreativesSteps()
                        .saveDefaultCanvasCreativesForClient(Long.parseLong(User.get(CLIENT_LOGIN).getClientID()));
        cpmAdGroupId = getCpmAdGroupWithDealsWithAdriverPixelBanner();
        retargetingListId = getRetargetingListsWithCryptaGoal(PUBLIC_GOAL_ID);
        api.userSteps.audienceTargetsSteps().addWithRetargetingList(CLIENT_LOGIN, cpmAdGroupId, retargetingListId);
    }

    private static Long getCpmAdGroupWithDealsWithAdriverPixelBanner() {
        Long cpmDealCampaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(CLIENT_LOGIN);
        api.userSteps.campaignFakeSteps().setType(cpmDealCampaignId, CampaignsType.CPM_DEALS);
        addForeignPlacements(cpmDealCampaignId);
        Long cpmAdGroupId = api.userSteps.adGroupsSteps()
                .addDefaultCpmBannerUserProfileAdGroup(cpmDealCampaignId, CLIENT_LOGIN);
        api.userSteps.adsSteps().addAd(new AdAddItemMap()
                        .withCpmBannerAdBuilderAd(new CpmBannerAdBuilderAdAddMap()
                                .withHref(CpmBannerAdBuilderAdAddMap.DEFAULT_HREF)
                                .withCreative(creativeIdForCpmBanners)
                                .withTrackingPixels(singletonList(PixelProvider.ADRIVER.testUrl())))
                        .withAdGroupId(cpmAdGroupId),
                CLIENT_LOGIN
        );
        return cpmAdGroupId;
    }

    private static void addForeignPlacements(Long cpmDealCampaignId) {
        api.userSteps.getDirectJooqDbSteps()
                .useShardForLogin(AGENCY_LOGIN)
                .placementsSteps()
                .addPlacement(BIG_PLACEMENT_PAGE_ID, 0);
        Long randomDealId = RandomUtils.nextLong(MIN_TEST_DEAL_ID, MAX_TEST_DEAL_ID);
        api.userSteps.getDirectJooqDbSteps()
                .useShardForLogin(AGENCY_LOGIN)
                .adfoxSteps()
                .addDeal(randomDealId, Long.parseLong(User.get(AGENCY_LOGIN).getClientID()),
                        getPlacementJsonsFromPageIds(singletonList(BIG_PLACEMENT_PAGE_ID)));
        api.userSteps.getDirectJooqDbSteps()
                .useShardForLogin(AGENCY_LOGIN)
                .dealsSteps()
                .addDeal(randomDealId, Long.parseLong(User.get(AGENCY_LOGIN).getClientID()));
        api.userSteps.getDirectJooqDbSteps()
                .useShardForLogin(CLIENT_LOGIN)
                .campaignDealsSteps()
                .addCampaignDeal(randomDealId, cpmDealCampaignId, 0);
    }

    private static Long getRetargetingListsWithCryptaGoal(Long goalId) {
        RetargetingListAddItemMap retargetingListAddItemMap = new RetargetingListAddItemMap()
                .withType(RetargetingListTypeEnum.AUDIENCE)
                .withName("Name" + RandomStringUtils.randomAlphabetic(3))
                .withDescription("Description" + RandomStringUtils.randomAlphabetic(3))
                .withRules(new RetargetingListRuleItemMap()
                        .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                .withMembershipLifeSpan(RandomUtils.nextInt(1, 90))
                                .withExternalId(goalId))
                        .withOperator(RetargetingListRuleOperatorEnum.ANY));
        Long retargetingListId = api.userSteps.retargetingListsSteps().add(CLIENT_LOGIN,
                new ru.yandex.autotests.directapi.model.api5.retargetinglists.AddRequestMap()
                        .withRetargetingLists(retargetingListAddItemMap)
        ).get(0);
        return retargetingListId;
    }

    @Test
    public void tryAddToCpmDealsWithPixelsNegativeTest() {
        api.userSteps.retargetingListsSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withRetargetingLists(
                        new RetargetingListUpdateItemMap()
                                .withId(retargetingListId)
                                .withRules(new RetargetingListRuleItemMap()
                                        .withOperator(RetargetingListRuleOperatorEnum.ANY)
                                        .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                .withExternalId(PRIVATE_GOAL_ID)
                                                .withMembershipLifeSpan(membershipLifeSpan)))),
                CLIENT_LOGIN,
                ExpectedResult.errors(new Notification(5004,
                        Api5ErrorDetailsJava.NO_RIGHTS_TO_PIXEL,
                        PixelProvider.ADRIVER.testUrl()))
        );
    }

    @Test
    public void tryAddToCpmDealsWithPixelsPositiveTest() {
        api.userSteps.retargetingListsSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withRetargetingLists(
                        new RetargetingListUpdateItemMap()
                                .withId(retargetingListId)
                                .withRules(new RetargetingListRuleItemMap()
                                        .withOperator(RetargetingListRuleOperatorEnum.ANY)
                                        .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                .withExternalId(PUBLIC_GOAL_ID)
                                                .withMembershipLifeSpan(membershipLifeSpan)))),
                CLIENT_LOGIN, ExpectedResult.success()
        );
    }
}
