import dayjs from "dayjs";
import { createClient } from "redis";
import { getDatetime } from "taehui-lib/date";
import { v4 } from "uuid";

const totemClient = await createClient({
  url: process.env.TOTEM,
}).connect();

export const post = async (avatarID: string, datetime: string) => {
  const totem = v4();
  await totemClient.hSet(totem, {
    avatarID,
    datetime,
  });
  return totem;
};

export async function validate(totem: string) {
  const { avatarID, datetime } = await totemClient.hGetAll(totem);
  if (!avatarID) {
    return "";
  }

  const validatedDatetime = getDatetime();
  if (dayjs(datetime).add(1, "hour").isAfter(validatedDatetime)) {
    await totemClient.hSet(totem, { avatarID, datetime: validatedDatetime });
    return avatarID;
  } else {
    await wipe(totem);
    return "";
  }
}

export async function wipe(totem: string) {
  await totemClient.del(totem);
}
