package ru.yandex.autotests.direct.db.steps;

import javax.annotation.ParametersAreNonnullByDefault;

import org.jooq.impl.DSL;

import ru.yandex.autotests.direct.db.steps.base.BasePpcSteps;
import ru.yandex.qatools.allure.annotations.Step;

import static ru.yandex.autotests.direct.db.models.jooq.ppc.Tables.CLIENTS;
import static ru.yandex.autotests.direct.db.models.jooq.ppc.Tables.INTERNAL_AD_PRODUCTS;

@ParametersAreNonnullByDefault
public class InternalAdProductSteps extends BasePpcSteps {
    private static final String INTERNAL_AD_PRODUCT_PERM = "internal_ad_product";

    @Step("DB: добавить запись в ppc.internal_ad_products, если её там нет ещё")
    public void ensureIsInternalAdProduct(Long clientId, String productName) {
        run(db -> {
            db.insertInto(INTERNAL_AD_PRODUCTS)
                    .set(INTERNAL_AD_PRODUCTS.CLIENTID, clientId)
                    .set(INTERNAL_AD_PRODUCTS.PRODUCT_NAME, productName)
                    .set(INTERNAL_AD_PRODUCTS.PRODUCT_DESCRIPTION, "test product: " + productName)
                    .onDuplicateKeyIgnore()
                    .execute();

            db.update(CLIENTS)
                    .set(CLIENTS.PERMS,
                            DSL.when(CLIENTS.PERMS.contains(INTERNAL_AD_PRODUCT_PERM), CLIENTS.PERMS)
                                    .when(CLIENTS.PERMS.eq(""), INTERNAL_AD_PRODUCT_PERM)
                                    .otherwise(DSL.concat(CLIENTS.PERMS, ", " + INTERNAL_AD_PRODUCT_PERM)))
                    .where(CLIENTS.CLIENTID.eq(clientId))
                    .execute();
        });
    }

    @Step("DB: получить название продукта внутренней рекламы из ppc.internal_ad_products")
    public String getInternalAdProductName(Long clientId) {
        return exec(db -> db.select(INTERNAL_AD_PRODUCTS.PRODUCT_NAME)
                .from(INTERNAL_AD_PRODUCTS)
                .where(INTERNAL_AD_PRODUCTS.CLIENTID.eq(clientId))
                .fetchOne(INTERNAL_AD_PRODUCTS.PRODUCT_NAME));
    }
}
