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

import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

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.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.AutoBudgetPromotion;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign;
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.StoriesNames;
import ru.yandex.autotests.directintapi.bstransport.TransportHelpSteps;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign.AUTO_BUDGET_PROMOTIONS;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Title("Транспорт: проверка отправки параметра AutoBudgetPromotions на уровне кампании")
@Stories(StoriesNames.CAMPAIGN_PARAMS_AUTOBUDGET_PROMOTIONS)
@Features(FeatureNames.CAMPAIGNS)
@Issue("https://st.yandex-team.ru/DIRECT-154022")
public class BsTransportOfAutoBudgetPromotionsTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final Short FIRST_PERCENT = 50;
    private static final Short SECOND_PERCENT = 200;
    private static final String FIRST_DATE_TO = "20211012";
    private static final String SECOND_DATE_TO = "20211015";
    private static final String FIRST_DATE_FROM = "20211112";
    private static final String SECOND_DATE_FROM = "20211112";
    private static final Long COEF = 10000L;

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

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

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

    private static TransportHelpSteps helpSteps = new TransportHelpSteps(api);

    private static int shard;

    private Long cid;
    private Long pid;
    private RunBsTransportScriptResponse resp;

    @BeforeClass
    public static void beforeClass() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        api.userSteps.getDirectJooqDbSteps().useShard(shard);
    }

    @Before
    @Step("Подготовка тестовых данных")
    public void before() {
        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long bid = api.userSteps.adsSteps().addDefaultTextAd(pid);
        Long keywordId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);
    }

    @Test
    @Title("Отсутствие AutoBudgetPromotions на уровне кампании, если в кампании нет промоакций")
    public void testTransportOfOrderTrafaretPositionBidCorrectionsOneGroupNoCoef() {
        resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Map<String, Map> orderMap = helpSteps.getOrderMap(resp, cid);
        assumeThat("в БК отправлен заказ (кампания)", orderMap, notNullValue());
        assertThat("в БК не отправлено поле AutoBudgetPromotions",
                orderMap.containsKey(AUTO_BUDGET_PROMOTIONS), equalTo(false));
    }

    @Test
    @Title("Отправка в БК поля AutoBudgetPromotions на уровне кампании, одна промоакция")
    public void testTransportOfOrderTrafaretPositionBidCorrectionsOneGroupSingleCoef() {
        api.userSteps.getDirectJooqDbSteps().campaignsPromotionsSteps()
                .addCampaignsPromotions(cid,
                        Date.valueOf(LocalDate.parse(FIRST_DATE_FROM, DateTimeFormatter.ofPattern("yyyMMdd"))),
                        Date.valueOf(LocalDate.parse(FIRST_DATE_TO, DateTimeFormatter.ofPattern("yyyMMdd"))),
                        FIRST_PERCENT);

        resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);

        AutoBudgetPromotion autoBudgetPromotion = new AutoBudgetPromotion()
                .withDateFrom(FIRST_DATE_FROM)
                .withDateTo(FIRST_DATE_TO)
                .withConversionBoostPercent(FIRST_PERCENT * COEF);
        List<AutoBudgetPromotion> expected = Collections.singletonList(autoBudgetPromotion);
        Campaign campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, cid);
        assertThat("отправленное в БК поле AutoBudgetPromotions на уровне кампании соответствует " +
                        "ожидаемому",
                campaign.getAutoBudgetPromotions(), beanDiffer(expected));
    }

    @Test
    @Title("Отправка в БК поля AutoBudgetPromotions на уровне кампании, две промоакции")
    public void testTransportOfOrderTrafaretPositionBidCorrectionsOneGroupMutlyCoef() {
        api.userSteps.getDirectJooqDbSteps().campaignsPromotionsSteps()
                .addCampaignsPromotions(cid,
                        Date.valueOf(LocalDate.parse(FIRST_DATE_FROM, DateTimeFormatter.ofPattern("yyyMMdd"))),
                        Date.valueOf(LocalDate.parse(FIRST_DATE_TO, DateTimeFormatter.ofPattern("yyyMMdd"))),
                        FIRST_PERCENT);
        api.userSteps.getDirectJooqDbSteps().campaignsPromotionsSteps()
                .addCampaignsPromotions(cid,
                        Date.valueOf(LocalDate.parse(SECOND_DATE_FROM, DateTimeFormatter.ofPattern("yyyMMdd"))),
                        Date.valueOf(LocalDate.parse(SECOND_DATE_TO, DateTimeFormatter.ofPattern("yyyMMdd"))),
                        SECOND_PERCENT);

        resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);

        AutoBudgetPromotion autoBudgetPromotion = new AutoBudgetPromotion()
                .withDateFrom(FIRST_DATE_FROM)
                .withDateTo(FIRST_DATE_TO)
                .withConversionBoostPercent(FIRST_PERCENT * COEF);
        AutoBudgetPromotion autoBudgetPromotionElse = new AutoBudgetPromotion()
                .withDateFrom(SECOND_DATE_FROM)
                .withDateTo(SECOND_DATE_TO)
                .withConversionBoostPercent(SECOND_PERCENT * COEF);
        List<AutoBudgetPromotion> expected = Arrays.asList(autoBudgetPromotion, autoBudgetPromotionElse);
        Campaign campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, cid);
        assertThat("отправленное в БК поле AutoBudgetPromotions на уровне кампании соответствует " +
                        "ожидаемому",
                campaign.getAutoBudgetPromotions(), beanDiffer(expected));
    }
}
