package ru.yandex.autotests.directintapi.bstransport.main.cpmbanner.transmit;

import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
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.cmd.rules.CreativeBannerRule;
import ru.yandex.autotests.direct.cmd.rules.DirectCmdRule;
import ru.yandex.autotests.direct.db.beans.campaign.StrategyData;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersPerformanceStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsAutobudget;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsPlatform;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsStrategyName;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.StrategiesType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampaignsRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.StrategiesRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.campaigns.CampaignTypeEnum;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.Money;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
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.datacontainers.jsonrpc.displaycanvas.ModerationInfo;
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.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
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.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 ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.core.IsNull.notNullValue;
import static ru.yandex.autotests.directintapi.bstransport.TransportUtils.CPM_COEF;
import static ru.yandex.autotests.directintapi.bstransport.TransportUtils.TRANSPORT_DATE_TIME_FORMATTER;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Description("Общая проверка отправки cpm стратегий с произвольным периодом")
@Features(FeatureNames.CPM_BANNER)
@Issue("https://st.yandex-team.ru/DIRECT-72162")
@RunWith(Parameterized.class)
public class SendingCpmStrategiesWithCustomPeriodCommonTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT_IMG_AD;
    private static final LocalDate START = LocalDate.now().plusDays(1);
    private static final LocalDate FINISH = LocalDate.now().plusDays(3);
    private static final Money AVG_CMP = MoneyCurrency.get(Currency.RUB).getMinCpmPrice();
    private static final Money BUDGET =
            MoneyCurrency.get(Currency.RUB).getMaxWeeklyBudgetAmount().divide(10f);

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

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

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

    @ClassRule
    public static DirectCmdRule defaultClassRule = DirectCmdRule.defaultClassRule();

    public CreativeBannerRule bannersRule = new CreativeBannerRule(CampaignTypeEnum.TEXT).withUlogin(LOGIN);

    @Rule
    public DirectCmdRule cmdRule = DirectCmdRule.defaultRule().withRules(bannersRule);

    private static int shard;
    private Long cid;
    private TransportHelpSteps helpSteps;

    @Parameterized.Parameter()
    public CampaignsStrategyName strategyName;

    @Parameterized.Parameter(1)
    public Double rfDecay;

    @Parameterized.Parameter(2)
    public Integer rfMinCPM;

    @Parameterized.Parameters(name = "Strategy = {0}")
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][]{
                {CampaignsStrategyName.autobudget_max_reach_custom_period, 0.16d, 0},
                {CampaignsStrategyName.autobudget_max_impressions_custom_period, 0d, 1},
        };
        return Arrays.asList(data);
    }

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

    @Before
    @Step("Подготовка тестовых данных")
    public void init() {
        cid = bannersRule.getCampaignId();
        Long creativeId = bannersRule.getCreativeId();
        Long bid = bannersRule.getBannerId();
        Long pid = bannersRule.getGroupId();
        Long keywordId = bannersRule.getCurrentGroup().getPhrases().get(0).getId();

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);
        DirectJooqDbSteps jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);
        helpSteps = new TransportHelpSteps(api).useDbJooqSteps(jooqDbSteps);
        jooqDbSteps.bannersPerformanceSteps()
                .setCreativeStatusModerate(cid, pid, bid, BannersPerformanceStatusmoderate.Yes);
        jooqDbSteps.perfCreativesSteps().setModerateInfo(creativeId,
                new ModerationInfo().generateTestData().toString());
        jooqDbSteps.perfCreativesSteps().setStatusModerate(creativeId, PerfCreativesStatusmoderate.Yes);
        api.userSteps.campaignStepsV5().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(cid)
                                .withTextCampaign(new TextCampaignUpdateItemMap()
                                        .withBiddingStrategy(new TextCampaignStrategyMap()
                                                .withSearch(new TextCampaignSearchStrategyMap().defaultServingOff())
                                                .withNetwork(new TextCampaignNetworkStrategyMap().defaultMaximumCoverage())))),
                ExpectedResult.success());
        CampaignsRecord campaignsRecord = jooqDbSteps.campaignsSteps().getCampaignById(cid);
        campaignsRecord.setStrategyName(strategyName);
        campaignsRecord.setPlatform(CampaignsPlatform.context);
        StrategyData strategyData = new StrategyData()
                .withName(strategyName)
                .withBudget(BUDGET.doubleValue())
                .withAvgCpm(AVG_CMP.doubleValue())
                .withStart(START.toString())
                .withFinish(FINISH.toString())
                .withAutoProlongation(1);
        campaignsRecord.setStrategyData(strategyData.toJsonElement());
        campaignsRecord.setAutobudget(CampaignsAutobudget.Yes);
        jooqDbSteps.campaignsSteps().updateCampaigns(campaignsRecord);

        Long strategyId =
                api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps().getCampaignById(cid).getStrategyId();
        if (strategyId != 0) {
            StrategiesRecord strategiesRecord =
                    api.userSteps.getDirectJooqDbSteps().useShard(shard).strategiesSteps().getStrategiesRecord(strategyId);
            strategiesRecord.setType(StrategiesType.valueOf(strategyName.getLiteral()));
            strategiesRecord.setStrategyData(strategyData.toJsonElement().toString());
            api.userSteps.getDirectJooqDbSteps().useShard(shard).strategiesSteps().updateStrategies(strategiesRecord);
        }
    }

    @Test
    public void testSendingStrategyWithCustomPeriod() {
        RunBsTransportScriptResponse resp =
                api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Campaign campaign
                = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
        TestSteps.assumeThat("в запросе есть кампания", campaign, notNullValue());

        Campaign expectedCampaign = helpSteps.buildExpectedCampaignObjFromDb(cid, shard, UpdateInfo.UPDATE);
        expectedCampaign.setAutoBudgetOptimizeRF(1);
        expectedCampaign.setRfDecay(rfDecay);
        expectedCampaign.setRfMinCPM(rfMinCPM);
        expectedCampaign.setAutoBudgetAvgCPMCur(AVG_CMP.addVAT().divide(CPM_COEF)
                .setScale(Campaign.PRECISION_DIGIT_COUNT_RUB, RoundingMode.HALF_UP)
                .floatValue());
        expectedCampaign.setAutoBudgetPeriodBudgetLimitCur(BUDGET.addVAT()
                .setScale(Campaign.PRECISION_DIGIT_COUNT_RUB, RoundingMode.HALF_UP)
                .floatValue());
        // здесь можно было бы также проверить значение AutoBudgetAvgCPM и AutoBudgetPeriodBudgetLimit,
        // но вычисление этих полей не пережило переход на НДС 20%, и теперь они вычисляются неправильно.
        // Это сознательно решили не исправлять, см. https://st.yandex-team.ru/DIRECT-88492
        expectedCampaign.setStartTime(START.atStartOfDay().format(TRANSPORT_DATE_TIME_FORMATTER));
        expectedCampaign.setAutoBudgetPeriodBudgetFinish(
                LocalDateTime.of(FINISH, LocalTime.MAX).format(TRANSPORT_DATE_TIME_FORMATTER));
        expectedCampaign.setAutoBudgetPeriodBudgetProlongation(1);

        assertThat("параметры стратегии соответсвуют ожиданиям",
                campaign,
                helpSteps.campaignReq1Matcher(expectedCampaign));
    }
}
