package ru.yandex.webmaster3.storage.spam;

import java.util.UUID;

import org.joda.time.Duration;
import org.joda.time.Instant;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
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;

@Repository
public class VerificationsForOwnerYDao extends AbstractYDao {
    private static final String TABLE_NAME = "verifications_for_owner";
    private static final Duration TTL = Duration.standardDays(60);

    public VerificationsForOwnerYDao() {
        super(PREFIX_INTERNAL, TABLE_NAME);
    }

    public long countVerifications(WebmasterHostId owner) {
        return countAll()
                .where(F.OWNER_HOST_ID.eq(owner))
                .and(F.UPDATE_TIME.gt(Instant.now().minus(TTL)))
                .queryOne();
    }

    public void addVerification(WebmasterHostId owner, UUID id) {
        upsert(
                F.OWNER_HOST_ID.value(owner),
                F.ID.value(id),
                F.UPDATE_TIME.value(Instant.now())
        ).execute();
    }

    private static class F {
        static final Field<WebmasterHostId> OWNER_HOST_ID = Fields.hostIdField("owner_host_id");
        static final Field<UUID> ID = Fields.uuidField("id");
        static final Field<Instant> UPDATE_TIME = Fields.jodaInstantField("update_time");
    }
}
