package ru.yandex.autotests.directintapi.bstransport.b2b.prepare;

import java.util.List;

import org.jooq.Condition;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersStatusarch;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesCreativeType;
import ru.yandex.autotests.direct.db.steps.base.LimitOffsetStepCallable;
import ru.yandex.autotests.directapi.ApiFeatures;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Title;

import static ru.yandex.autotests.direct.db.models.jooq.ppc.Tables.BANNERS;
import static ru.yandex.autotests.direct.db.models.jooq.ppc.Tables.BANNERS_PERFORMANCE;
import static ru.yandex.autotests.direct.db.models.jooq.ppc.Tables.CAMPAIGNS;
import static ru.yandex.autotests.direct.db.models.jooq.ppc.Tables.PERF_CREATIVES;

/**
 * User: gerdler
 * https://st.yandex-team.ru/DIRECT-74256
 */
@Aqua.Test
@Title("Кампании частные сделки с HTML5-креативом")
@Features(ApiFeatures.NOT_REGRESSION_YET)
public class CpmDealsCampaignsWithHTML5CreativePrepareTest extends BaseCampaignsB2BPrepareTest {

    @Override
    protected LimitOffsetStepCallable<List<Long>> getCampaignsCallable(Condition baseCondition) {
        // Order by сильно замедляет запрос, поэтому просто смотрим в последней четверти кампаний
        // Это может привести к неожиданным результатам при движении limit и offset, но мы готовы к этому
        return (db, limit, offset) -> db.selectDistinct(CAMPAIGNS.CID)
                .from(PERF_CREATIVES)
                .straightJoin(BANNERS_PERFORMANCE).on(BANNERS_PERFORMANCE.CREATIVE_ID.eq(PERF_CREATIVES.CREATIVE_ID))
                .straightJoin(BANNERS).on(BANNERS.BID.eq(BANNERS_PERFORMANCE.BID))
                .join(CAMPAIGNS).on(CAMPAIGNS.CID.eq(BANNERS.CID))
                .where(baseCondition
                        .and(CAMPAIGNS.ORDERID.gt(0L))
                        .and(CAMPAIGNS.CID.gt(getLastProdCidDirectBalance() / 5))
                        .and(CAMPAIGNS.TYPE.eq(CampaignsType.cpm_deals))
                        .and(BANNERS.BANNERID.gt(0L))
                        .and(BANNERS.STATUSARCH.ne(BannersStatusarch.No)))
                        .and(PERF_CREATIVES.CREATIVE_TYPE.eq(PerfCreativesCreativeType.html5_creative))
                .limit(offset, limit)
                .fetch(CAMPAIGNS.CID);
    }
}