package ru.yandex.webmaster3.storage.mirrors.dao;

import lombok.Data;
import org.jetbrains.annotations.Nullable;
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.Delete;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.DataMapper;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;

/**
 * @author leonidrom
 */
@Repository
public class MirrorChangeDisallowedOwnersYDao extends AbstractYDao {
    public static final String TABLE_NAME = "mirror_change_disallowed_owners";

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

    @Nullable
    public Record get(WebmasterHostId owner) {
        var sel = select(MAPPER).where(F.OWNER.eq(owner.getPunycodeHostname()));
        return queryOne(sel.getStatement(), MAPPER);
    }

    public void clearOldRecords(long minTimestamp) {
        Delete delete = delete();
        delete.where(F.UPDATE_DATE.lt(minTimestamp));
        execute(delete);
    }

    @Data
    public static class Record {
        public final String owner;
        public final String threat;
        public final long updateDate;
    }

    private static class F {
        public static Field<String> OWNER = Fields.stringField("owner");
        public static Field<String> THREAT = Fields.stringField("threat");
        public static Field<Long> UPDATE_DATE = Fields.unsignedLongField("update_date");
    }

    private static final DataMapper<Record> MAPPER = DataMapper.create(F.OWNER, F.THREAT, F.UPDATE_DATE, Record::new);
}
