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

import java.util.List;

import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.RetargetingGoalsRecord;
import ru.yandex.autotests.direct.db.steps.base.BasePpcSteps;
import ru.yandex.qatools.allure.annotations.Step;

import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.direct.db.models.jooq.ppc.Tables.RETARGETING_GOALS;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;


public class RetargetingGoalsSteps extends BasePpcSteps {
    @Step("DB: получение записей из ppc.retargeting_goals для ret_cond_id = {0}")
    public List<RetargetingGoalsRecord> getRetargetingGoalsByRetCondId(Long retCondId) {
        return exec(db -> db.selectFrom(RETARGETING_GOALS)
                .where(RETARGETING_GOALS.RET_COND_ID.eq(retCondId))
                .fetch());
    }

    @Step("DB: получение записей из ppc.retargeting_goals для ret_cond_id = {0} и goal_id = {1}")
    public RetargetingGoalsRecord getRetargetingGoals(Long retCondId, Long goalId) {
        return exec(db -> db.selectFrom(RETARGETING_GOALS)
                .where(RETARGETING_GOALS.RET_COND_ID.eq(retCondId)
                        .and(RETARGETING_GOALS.GOAL_ID.eq(goalId)))
                .fetchOne());
    }

    @Step("DB: установка флага is_accessible в таблице ppc.retargeting_goals " +
            "(ret_cond_id = {0}, goal_id = {1}, is_accessible = {2})")
    public void setIsAccessible(Long retCondId, Long goalId, int isAccessible) {
        RetargetingGoalsRecord retargetingGoals = getRetargetingGoals(retCondId, goalId);
        assumeThat("найдена цель с указанными ret_cond_id & goal_id", retargetingGoals, notNullValue());
        run(db -> db.update(RETARGETING_GOALS)
                .set(RETARGETING_GOALS.IS_ACCESSIBLE, isAccessible)
                .where(RETARGETING_GOALS.RET_COND_ID.eq(retCondId)
                        .and(RETARGETING_GOALS.GOAL_ID.eq(goalId)))
                .execute());
    }

    @Step("DB: добавление записи в таблицу ppc.retargeting_goals")
    public void addRetargetingGoals(RetargetingGoalsRecord retargetingGoals) {
        exec(db -> db.insertInto(RETARGETING_GOALS)
                .set(retargetingGoals)
                .execute());
    }

    @Step("DB: подмена goal_id в таблице ppc.retargeting_goals" +
          "(ret_cond_id = {0}, old_goal_id = {1}, new_goal_id = {2})")
    public void substititeGoalId(Long retCondId, Long oldGoalId, Long newGoalId) {
        run(db -> db.update(RETARGETING_GOALS)
                .set(RETARGETING_GOALS.GOAL_ID, newGoalId)
                .where(RETARGETING_GOALS.RET_COND_ID.eq(retCondId)
                        .and(RETARGETING_GOALS.GOAL_ID.eq(oldGoalId)))
                .execute());
    }
}
