package ru.yandex.webmaster3.storage.spam;

import java.util.List;
import java.util.UUID;

import org.jetbrains.annotations.NotNull;
import org.joda.time.Instant;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.data.WebmasterUser;
import ru.yandex.webmaster3.core.spam.CaptchaEvent;
import ru.yandex.webmaster3.core.spam.ShowCaptchaReason;
import ru.yandex.webmaster3.storage.user.UserTakeoutDataProvider;
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 CaptchaEventsYDao extends AbstractYDao implements UserTakeoutDataProvider {
    private static final String TABLE_NAME = "captcha_events";

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

    public void addRecord(long userId, String reqId, UUID eventId, String ip, WebmasterHostId hostId, CaptchaEvent event, ShowCaptchaReason reason, String action) {
        upsert(
                F.USER_ID.value(userId),
                F.REQ_ID.value(reqId),
                F.EVENT_ID.value(eventId),
                F.IP.value(ip),
                F.HOST_ID.value(hostId),
                F.EVENT.value(event),
                F.REASON.value(reason),
                F.ACTION.value(action),
                F.UPDATE_TIME.value(Instant.now())
        )
                .execute();
    }

    public void deleteForUser(long userId) {
        delete().where(F.USER_ID.eq(userId)).execute();
    }

    @Override
    public void deleteUserData(WebmasterUser user) {
        deleteForUser(user.getUserId());
    }

    @Override
    public @NotNull List<String> getTakeoutTables() {
        return List.of(
                getTablePath()
        );
    }

    private static final class F {
        static final Field<Long> USER_ID = Fields.longField("user_id");
        static final Field<String> REQ_ID = Fields.stringField("req_id");
        static final Field<UUID> EVENT_ID = Fields.uuidField("event_id");
        static final Field<String> IP = Fields.stringField("ip");
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        static final Field<CaptchaEvent> EVENT = Fields.stringEnumField("event", CaptchaEvent.R);
        static final Field<ShowCaptchaReason> REASON = Fields.stringEnumField("reason", ShowCaptchaReason.R).makeOptional();
        static final Field<String> ACTION = Fields.stringField("action");
        static final Field<Instant> UPDATE_TIME = Fields.jodaInstantField("update_time"); // TTL 60 days
    }
}
