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

import org.springframework.stereotype.Repository;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
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;

import java.util.UUID;


/**
 * Created by kravchenko99 on 02.11.21.
 */
@Repository
public class TokensForUnsubscribeYDao extends AbstractYDao {
    public TokensForUnsubscribeYDao() {
        super(PREFIX_NOTIFICATION, "tokens_for_unsubscribe");
    }

    public void insert(String token, long userId, UUID messageUid) {
        upsert(
                F.TOKEN.value(token),
                F.USER_ID.value(userId),
                F.MESSAGE_ID.value(messageUid)
        ).execute();
    }

    public void deleteForUser(long userId) {
        var sel = select(PK_MAPPER).secondaryIndex("user_id_index").where(F.USER_ID.eq(userId)).getStatement();
        delete().on(sel).execute();
    }

    public Long getUserId(String token) {
        return select(F.USER_ID)
                .where(F.TOKEN.eq(token))
                .queryOne();
    }

    private static final DataMapper<String> PK_MAPPER = DataMapper.create(F.TOKEN, id -> id);

    private static final class F {
        public static final Field<String> TOKEN = Fields.stringField("user_token");
        public static final Field<Long> USER_ID = Fields.longField("user_id");
        public static final Field<UUID> MESSAGE_ID = Fields.uuidField("message_id");
    }
}
