package ru.yandex.autotests.directintapi.bstransport.main.campaign.parameters.s2stracking;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.MobileAppsStoreType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.MobileContentOsType;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.db.steps.JooqCampaignsOpts;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
import ru.yandex.autotests.directapi.darkside.model.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.PriorityGoalsItemMap;
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.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.MobileContentCleanupRule;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static java.util.Collections.singletonList;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static ru.yandex.autotests.direct.db.steps.MobileAppSteps.getDefaultMobileAppsRecord;
import static ru.yandex.autotests.directapi.darkside.model.MobileContentUtils.getDefaultMobileContent;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: отправка s2s трекерных ссылок для целей из чужих доступных приложений")
@Features(FeatureNames.CAMPAIGNS)
@RunWith(Parameterized.class)
public class BsTransportS2sTrackingSharedGoalsTest {
    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final String OWNER_LOGIN = Logins.LOGIN_MAIN;

    private static final String IOS_STORE_CONTENT_ID = "id" + randomNumeric(10);

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(LOGIN);
    private static final DirectJooqDbSteps jooqDbSteps = new DirectJooqDbSteps().useShardForLogin(LOGIN);
    private static final Long clientId = jooqDbSteps.shardingSteps().getClientIdByLogin(LOGIN);
    private static final int shard = jooqDbSteps.shardingSteps().getShardByLogin(LOGIN);

    @ClassRule
    public static ApiSteps ownerApi = new ApiSteps().as(OWNER_LOGIN); // для владельца мобильных приложений
    private static final DirectJooqDbSteps ownerJooqDbSteps = new DirectJooqDbSteps().useShardForLogin(OWNER_LOGIN);
    private static final Long ownerClientId = ownerJooqDbSteps.shardingSteps().getClientIdByLogin(OWNER_LOGIN);
    private static final int ownerShard = ownerJooqDbSteps.shardingSteps().getShardByLogin(OWNER_LOGIN);
    @ClassRule
    public static MobileContentCleanupRule mobileCleanupRule = new MobileContentCleanupRule(ownerApi);

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


    private static final Long iosGoalId = createMobileAppAndGoal();

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

    public Long cid;

    @BeforeClass
    public static void beforeClass() {
        assumeThat("Важно проверить транспорт, когда клиенты на разных шардах",
                shard, is(not(equalTo(ownerShard))));
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        ownerJooqDbSteps.mobileAppsSteps().addMobileGoalsAccess(clientId, ownerClientId);
    }

    @Parameterized.Parameter(0)
    public String description;

    @Parameterized.Parameter(1)
    public CampaignAddItemMap campaignAddItemMap;

    @Parameterized.Parameters(name = "Description - {0}")
    public static Collection data() {
        Object[][] data = new Object[][]{
                {"With default strategy",
                        new CampaignAddItemMap().defaultCampaignAddItem()
                                .withTextCampaign((new TextCampaignAddItemMap())
                                .withPriorityGoals(new PriorityGoalsItemMap()
                                        .withGoalId(iosGoalId)
                                        .withValue(125_000_000L))
                                .withBiddingStrategy((new TextCampaignStrategyAddMap())
                                        .withSearch(new TextCampaignSearchStrategyAddMap().defaultHighestPosition())
                                        .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultNetworkDefault())))},
                {"With goalId=13",
                        new CampaignAddItemMap().defaultCampaignAddItem()
                                .withTextCampaign((new TextCampaignAddItemMap())
                                .withBiddingStrategy((new TextCampaignStrategyAddMap())
                                        .withSearch(new TextCampaignSearchStrategyAddMap().defaultAverageCpa(Currency.RUB, iosGoalId))
                                        .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultNetworkDefault())))},
        };
        return Arrays.asList(data);
    }

    @Before
    public void before() {
        jooqDbSteps.featuresSteps().ensureClientHasFeature(clientId, "in_app_mobile_targeting");
        cid = api.as(LOGIN).userSteps.campaignSteps().addCampaign(campaignAddItemMap);
        jooqDbSteps.campaignsSteps().setOpts(cid, singletonList(JooqCampaignsOpts.S2S_TRACKING_ENABLED));
        api.as(LOGIN).userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
    }

    @Test
    public void testS2sTrackingUrlTransport() {
        RunBsTransportScriptResponse resp =
                api.as(LOGIN).userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Campaign campaign =
                api.as(LOGIN).userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, cid);
        assumeThat("кампания отправляется в БК", campaign, notNullValue());
        assertThat("значение S2STrackingURLs отправляется верным",
                campaign.getS2sTrackingUrls(), hasEntry(equalTo("IOS"),
                        startsWith(createIosTrackingUrlPrefix(cid))));
    }

    private static String createIosTrackingUrlPrefix(Long cid) {
        return "https://app.appsflyer.com/" + IOS_STORE_CONTENT_ID + "?is_retargeting" +
                "=true&idfa={IDFA_UC}&af_c_id=" + cid + "&clickid={TRACKID" +
                "}&pid=yandexdirect_int&af_ip={CLIENTIP}&af_lang={DEVICE_LANG}&af_ua" +
                "={USER_AGENT}&redirect=false";
    }

    private static Long createMobileAppAndGoal() {
        Long iosMobileContentId = ownerJooqDbSteps.mobileContentSteps().saveMobileContent(
                getDefaultMobileContent(ownerClientId.toString())
                        .setStoreContentId(IOS_STORE_CONTENT_ID)
                        .setOsType(MobileContentOsType.iOS));
        Long iosMobileAppId = ownerJooqDbSteps.mobileAppsSteps().createMobileApp(
                getDefaultMobileAppsRecord(ownerClientId, iosMobileContentId)
                        .setStoreType(MobileAppsStoreType.AppleAppStore));
        Long iosGoalId = ownerJooqDbSteps.mobileAppsSteps().addMobileAppGoal(iosMobileAppId);

        mobileCleanupRule.setShard(ownerShard);
        mobileCleanupRule.setMobileContentIds(singletonList(iosMobileContentId));
        mobileCleanupRule.setMobileAppIdsToDeleteAfterTest(ownerClientId, singletonList(iosMobileAppId));
        return iosGoalId;
    }
}
