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

import java.sql.Timestamp;
import java.time.Instant;
import java.util.stream.Stream;

import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.AutobudgetAlertsRecord;
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.AutobudgetAlerts.AUTOBUDGET_ALERTS;

public class AutoBudgetAlertsSteps extends BasePpcSteps {
    //problems flags description: https://direct-dev.yandex-team.ru/db/ppc/tables/autobudget_alerts.html
    public enum ProblemsEnum {
        NO_PROBLEMS(0),
        IN_ROTATION(1),
        MAX_BID_REACHED(1 << 1),
        MARGINAL_PRICE_REACHED(1 << 2),
        UPPER_POSITIONS_REACHED(1 << 3),
        ENGINE_MIN_COST_LIMITED(1 << 4),
        LIMITED_BY_BALANCE(1 << 5),
        NO_BANNERS(1 << 6),
        LIMIT_BY_AVG_COST(1 << 7),
        WALLET_DAILY_BUDGET_REACHED(1 << 8);

        short value;

        ProblemsEnum(int value) {
            this.value = (short) value;
        }

        public short getValue() {
            return value;
        }

        public static short getResultProblemValue(ProblemsEnum... problems) {
            return Stream.of(problems)
                    .map(ProblemsEnum::getValue)
                    .reduce(NO_PROBLEMS.getValue(), (a, b) -> (short) (a | b));
        }
    }

    public void addOrUpdateAlert(Long cid, ProblemsEnum... problems) {
        addOrUpdateAutoBudgetAlertsRecord(
                new AutobudgetAlertsRecord()
                        .setCid(cid)
                        .setLastUpdate(Timestamp.from(Instant.now()))
                        .setOverdraft(0L)
                        .setProblems(ProblemsEnum.getResultProblemValue(problems)));
    }

    @Step("DB: добавление записи в таблицу ppc.autobudget_alerts")
    public void addOrUpdateAutoBudgetAlertsRecord(AutobudgetAlertsRecord autoBudgetAlertsRecord) {
        run(db -> db.insertInto(AUTOBUDGET_ALERTS)
                .set(autoBudgetAlertsRecord)
                .onDuplicateKeyUpdate()
                .set(autoBudgetAlertsRecord)
                .execute()
        );
    }

    @Step("DB: получение записи из таблицы ppc.autobudget_alerts (cid = {0})")
    public AutobudgetAlertsRecord getAutobudgetAlertsRecord(Long cid) {
        return exec(db ->
                db.selectFrom(AUTOBUDGET_ALERTS)
                .where(AUTOBUDGET_ALERTS.CID.eq(cid))
                .fetchAny());
    }
}
