package ru.yandex.autotests.directintapi.bstransport.main.internalads;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.ParametersAreNonnullByDefault;

import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.cmd.rules.CampaignRule;
import ru.yandex.autotests.direct.cmd.rules.DirectCmdRule;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BsExportQueueRecord;
import ru.yandex.autotests.direct.scriptrunner.service.clientdata.ClientDataParams;
import ru.yandex.autotests.direct.utils.campaigns.CampaignTypeEnum;
import ru.yandex.autotests.direct.utils.config.DirectTestRunProperties;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.model.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.bslogs.UpdateInfo;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign;
import ru.yandex.autotests.directapi.darkside.steps.ScriptParamsProfiles;
import ru.yandex.autotests.directapi.darkside.steps.TransportSteps;
import ru.yandex.autotests.directapi.darkside.steps.fakesteps.ClientFakeSteps;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.TransportHelpSteps;
import ru.yandex.autotests.irt.testutils.allure.TestSteps;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;

import static org.hamcrest.Matchers.notNullValue;
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)
@Tag(TagDictionary.TRUNK)
@Description("Проверяем отправку ServiceName на двух кампаниях внутренней рекламы в разных продуктах")
@Features(FeatureNames.INTERNAL_ADS)
@Issue("https://st.yandex-team.ru/DIRECT-95488")
@ParametersAreNonnullByDefault
public class InternalAdsServiceNameTwoProductsTransportTest {
    private static final String LOGIN_PRODUCT_1 = Logins.LOGIN_TRANSPORT_INTERNAL_ADS;
    private static final String LOGIN_PRODUCT_2 = Logins.LOGIN_TRANSPORT_INTERNAL_ADS2;
    private static final String TRANSPORT_PROFILE_NAME = ScriptParamsProfiles.ProfileNames.INTERNAL_ADS.toString();

    public CampaignRule campaignRuleForProduct1 = new CampaignRule()
            .withMediaType(CampaignTypeEnum.INTERNAL_DISTRIB)
            .withUlogin(LOGIN_PRODUCT_1);

    public CampaignRule campaignRuleForProduct2 = new CampaignRule()
            .withMediaType(CampaignTypeEnum.INTERNAL_FREE)
            .withUlogin(LOGIN_PRODUCT_2);

    @Rule
    public DirectCmdRule cmdRule = DirectCmdRule.defaultRule()
            .withRules(campaignRuleForProduct1, campaignRuleForProduct2);

    @Rule
    public InternalAdsBaseTest.EnsureInternalAdProductPresentRule ensureInternalAdProduct1PresentRule =
            new InternalAdsBaseTest.EnsureInternalAdProductPresentRule(LOGIN_PRODUCT_1);

    @Rule
    public InternalAdsBaseTest.EnsureInternalAdProductPresentRule ensureInternalAdProduct2PresentRule =
            new InternalAdsBaseTest.EnsureInternalAdProductPresentRule(LOGIN_PRODUCT_2);

    @ClassRule
    public static ApiSteps api = new ApiSteps();
    private Long cidInProduct1;
    private Long cidInProduct2;
    private int shard;
    private TransportSteps transportSteps;
    private ScriptParamsProfiles clientDataParamsProfiles;

    @Before
    public void setUp() {
        transportSteps = api.userSteps.getDarkSideSteps().getTransportSteps();
        clientDataParamsProfiles = new ScriptParamsProfiles(DirectTestRunProperties.getInstance());

        cidInProduct1 = campaignRuleForProduct1.getCampaignId();
        cidInProduct2 = campaignRuleForProduct2.getCampaignId();

        ClientFakeSteps clientFakeSteps = api.userSteps.getDarkSideSteps().getClientFakeSteps();
        shard = clientFakeSteps.getUserShard(LOGIN_PRODUCT_1);

        if (clientFakeSteps.getUserShard(LOGIN_PRODUCT_2) != shard) {
            clientFakeSteps.reshardUserWithLock(LOGIN_PRODUCT_2, shard);
        }

        api.userSteps.campaignFakeSteps().makeCampaignInternalReadyForSendingToBS(cidInProduct1);
        api.userSteps.campaignFakeSteps().makeCampaignInternalReadyForSendingToBS(cidInProduct2);
    }

    @Test
    public void sendCampaignsFromTwoDifferentProducts() {
        TransportHelpSteps helpSteps = new TransportHelpSteps(api);
        RunBsTransportScriptResponse resp = sendCampaigns(cidInProduct1, cidInProduct2);

        for (Long cid : Arrays.asList(cidInProduct1, cidInProduct2)) {
            Campaign campaign = transportSteps.getClientDataRequestCampaign(resp, 0, cid);
            Campaign expectedCampaign = helpSteps.buildExpectedCampaignObjFromDb(cid, shard, UpdateInfo.UPDATE);

            assumeThat("в БК отправлена кампания", campaign, notNullValue());
            assertThat("Значение параметров кампании соответствует ожидаениям",
                    campaign,
                    helpSteps.campaignReq1Matcher(expectedCampaign));
        }
    }

    private RunBsTransportScriptResponse sendCampaigns(Long... cids) {
        for (Long cid : cids) {
            transportSteps.runBsExportMasterScript(shard, cid);
            BsExportQueueRecord bsExportQueueRecord = api.userSteps.getDirectJooqDbSteps().useShard(shard)
                    .transportSteps().getBsExportQueueRecord(cid);
            TestSteps.assumeThat("кампания попала в очередь ppc.bs_export_queue", bsExportQueueRecord, Matchers.notNullValue());
        }

        ClientDataParams params = clientDataParamsProfiles.getProfileClone(TRANSPORT_PROFILE_NAME)
                .withCid(Stream.of(cids).map(Long::intValue).collect(Collectors.toList()))
                .withShardId(shard);

        RunBsTransportScriptResponse resp = transportSteps.runBsClientDataScript(params);
        TestSteps.assumeThat("ответ ручки запуска скрипта содержит ссылку на запуск",
                resp, Matchers.notNullValue());
        TestSteps.assumeThat("ответ ручки запуска скрипта содержит массив uuid (ссылки на логи экспорта)",
                resp.getUuid(), Matchers.notNullValue());
        TestSteps.assumeThat("ответ ручки запуска скрипта содержит не пустой массив uuid (ссылки на логи экспорта)",
                Arrays.asList(resp.getUuid()), Matchers.not(Matchers.empty()));

        for (Long cid : cids) {
            Map<String, Map> log = transportSteps.getRawClientDataLogEntriesForCampaign(resp, cid);
            TestSteps.assumeThat("ответ ручки запуска скрипта содержит ссылки на логи обеих итераций экспорта",
                    Arrays.asList(resp.getUuid()), Matchers.hasSize(2));
            TestSteps.assumeThat("в логах присутствуют 2 итерации транспорта в БК",
                    log.keySet(), Matchers.allOf(Matchers.notNullValue(), Matchers.hasSize(2)));
        }

        return resp;
    }
}
