import { d as defineMiddleware } from './index_DXggy6V9.mjs';
import { jwtVerify, errors } from 'jose';

const TOKEN = "token";
const PROTECTED_ROUTES = ["/api/chat/reply", "/api/auth/register"];
const secret = new TextEncoder().encode(undefined                              );
const verifyAuth = async (token) => {
  if (!token) {
    return {
      status: "unauthorized",
      msg: "Please pass a request token"
    };
  }
  try {
    const jwtVerifyResult = await jwtVerify(token, secret);
    console.log({ jwtVerifyResult });
    return {
      status: "authorized",
      payload: jwtVerifyResult.payload,
      msg: "successfully verified auth token"
    };
  } catch (err) {
    if (err instanceof errors.JOSEError) {
      return { status: "error", msg: err.message };
    }
    return { status: "error", msg: "could not validate auth token" };
  }
};
const onRequest = defineMiddleware(
  async ({ url, cookies, redirect, locals }, next) => {
    const isDashboard = url.pathname.startsWith("/dashboard");
    if (!isDashboard) return next();
    const token = cookies?.get(TOKEN)?.value;
    const { status, msg, payload } = await verifyAuth(token);
    console.log({
      token,
      status,
      msg,
      payload
    });
    if (!locals.user)
      locals.user = payload?.user;
    if (!PROTECTED_ROUTES.includes(url.pathname)) {
      if (url.pathname.startsWith("/api/auth") || url.pathname.startsWith("/dashboard/register") || url.pathname.startsWith("/dashboard/logout"))
        return next();
    }
    if (status === "authorized")
      if (url.pathname.startsWith("/dashboard/login"))
        return redirect("/dashboard");
      else if (
        // @ts-ignore
        !locals?.user?.isAdmin && url.pathname.startsWith("/dashboard/staffs")
      )
        return redirect("/dashboard");
      else return next();
    else if (status === "error" || status === "unauthorized") {
      if (/^\/dashboard\/(login|forgot-password|reset-password)/.test(
        url.pathname
      ))
        return next();
      if (url.pathname.startsWith("/api/") && PROTECTED_ROUTES.includes(url.pathname)) {
        return new Response(JSON.stringify({ message: msg }), {
          status: 401
        });
      } else if (isDashboard) {
        return Response.redirect(new URL("/dashboard/login", url));
      }
    }
    return Response.redirect(new URL("/", url));
  }
);

export { TOKEN as T, onRequest as o };
