import { getAvatar } from "@/app/www/system/DB";
import { validate } from "@/app/www/system/Totem";
import { NextRequest } from "next/server";

export default function validateTotem(
  route: (
    req: NextRequest,
    params: { params: Record<string, string> },
  ) => Promise<Response>,
) {
  return async (
    req: NextRequest,
    params: { params: Record<string, string> },
  ) => {
    const totem = req.headers.get("totem");
    if (!totem) {
      return new Response(undefined, { status: 400 });
    }

    const avatarID = await validate(totem);
    if (avatarID) {
      const avatar = await getAvatar(avatarID);
      if (avatar) {
        const { avatarID, avatarName, level, fax, avatarIntro } = avatar;
        req.headers.set("avatarID", avatarID);
        req.headers.set("avatarName", encodeURIComponent(avatarName));
        req.headers.set("level", level.toString());
        req.headers.set("fax", encodeURIComponent(fax));
        req.headers.set("avatarIntro", encodeURIComponent(avatarIntro));
        return route(req, params);
      }
    }

    return new Response(undefined, { status: 401 });
  };
}
