import { NextResponse } from "next/server";
import { validateAdmin } from "@/middlewares/validate.admin.js";
import { postViewCounting } from "./middlewares/post.view.counting";
import { forbiddenRoute } from "./middlewares/forbidden.route";
import { joinBridgeMiddleware } from "./middlewares/join.bridge";

export default async function proxy(request) {
  const cookies = Object.fromEntries(
    request.cookies.getAll().map((c) => Object.values(c))
  );

  const roles = [
    {
      execute: async () => await forbiddenRoute(request),
      url: ["/forbidden"],
    },
    {
      execute: async () => await postViewCounting(request),
      url: ["/post"],
    },
    {
      execute: async () => await validateAdmin(request),
      url: ["/dashboard", "/api/upload", "/api/admin"],
    },
    {
      execute: async () => await joinBridgeMiddleware(request),
      url: ["/api/bridge"],
    },
    {
      execute: async () => {
        const next = NextResponse.next();

        if (cookies.refreshToken && cookies.accessToken)
          return NextResponse.redirect(new URL("/dashboard", request.url));

        return next;
      },
      url: ["/login"],
    },
    {
      execute: async () => {
        if (!cookies.refreshToken || !cookies.accessToken)
          return NextResponse.redirect(new URL("/login", request.url));

        return NextResponse.redirect(new URL("/dashboard", request.url));
      },
      url: ["/monggopinarak"],
    },
  ];

  const middleware = roles.find((role) =>
    role.url.some((url) => request.nextUrl.pathname.startsWith(url))
  );
  if (middleware) return middleware.execute();
  return NextResponse.next();
}

export const config = {
  matcher: [
    "/monggopinarak",
    "/dashboard/:path*",
    "/api/upload/:path*",
    "/api/admin/:path*",
    "/api/bridge/:path*",
    "/login",
    "/post/:path*",
    "/forbidden",
  ],
};
