import { Middleware } from "koa";
import dayjs from "dayjs";
import { getDatetime } from "taehui-ts/date";

import DB from "src/system/DB";

export const validateTotem: (isSilent: boolean) => Middleware =
  (isSilent) => async (ctx, next) => {
    const {
      headers: { totem },
    } = ctx;

    const totemText = totem as string;

    const data = await DB.ta(async (db) => {
      const data = await DB.getAvatarAsTotem(db, totemText);

      if (data) {
        const datetime = getDatetime();
        if (dayjs(data.date).add(1, "hour").isAfter(datetime)) {
          await DB.setTotemDateAsTotem(db, totemText, datetime);
          return DB.getAvatarAsAvatarID(db, data.avatarID);
        } else {
          await DB.wipeTotem(db, totemText);
        }
      }
    });

    if (data) {
      ctx.headers.avatarID = data.avatarID;
      ctx.headers.avatarName = data.avatarName;
      ctx.headers.level = String(data.level);
      ctx.headers.fax = data.fax;
      ctx.headers.avatarIntro = data.avatarIntro;
      await next();
    } else {
      ctx.body = { isSilent };
      ctx.status = 401;
    }
  };
