package ru.yandex.webmaster3.storage.verification.auto;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.data.WebmasterUser;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;

/**
 * @author avhaliullin
 */
@Slf4j
@Repository
public class AutoVerificationYDao extends AbstractYDao {
    public AutoVerificationYDao() {
        super(PREFIX_VERIFICATION, "auto_verification");
    }

    public void deleteRecord(long userId, WebmasterHostId hostId) {
        delete()
                .where(F.HOST_ID.eq(hostId))
                .and(F.USER_ID.eq(userId))
                .execute();
    }

    public void insertRecord(long userId, WebmasterHostId hostId) {
        insert(
                F.USER_ID.value(userId),
                F.HOST_ID.value(hostId)
        ).execute();
    }

    public boolean hasRecord(long userId, WebmasterHostId hostId) {
        return select(F.USER_ID)
                .where(F.USER_ID.eq(userId))
                .and(F.HOST_ID.eq(hostId))
                .limit(1)
                .queryForList()
                .size() > 0;
    }

    public void deleteForUser(WebmasterUser user) {
        delete().where(F.USER_ID.eq(user.getUserId())).execute();
    }

    private static class F {
        static final Field<Long> USER_ID = Fields.longField("user_id");
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
    }
}
