import dayjs from "dayjs";
import { NextRequest } from "next/server";
import { getMillis } from "taehui-lib/date";

export default function validateMillis(
  route: (
    request: NextRequest,
    params: { params: Record<string, string> },
  ) => Promise<Response>,
) {
  return async (
    req: NextRequest,
    params: { params: Record<string, string> },
  ) => {
    const { headers } = req;

    const millis = headers.get("millis");
    if (!millis) {
      return new Response(undefined, {
        status: 400,
      });
    }

    if (dayjs(Number(millis)).add(1, "minute").isBefore(getMillis())) {
      return new Response(undefined, {
        status: 401,
      });
    }

    return route(req, params);
  };
}
