
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

// This function can be marked `async` if using `await` inside
export const middleware = async (request: NextRequest) => {
  console.log("middleware");
  console.log(request.method);
  console.log(request.url);

  const origin = request.headers.get("origin");
  console.log(origin);

  const { pathname } = request.nextUrl;

  // CROS
  const corsRespone = handleCors(request);
  if (corsRespone) {
    return setCorsHeaders(
      NextResponse.redirect(new URL("/login", request.url))
    );
  }
};

function handleCors(req: NextRequest): NextResponse | null {
  if (req.method === "OPTIONS") {
    return new NextResponse(null, {
      status: 204,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
        "Access-Control-Allow-Headers": "Content-Type, Authorization",
        "Access-Control-Max-Age": "86400",
      },
    });
  }
  return null;
}

function setCorsHeaders(res: NextResponse): NextResponse {
  res.headers.set("Access-Control-Allow-Origin", "*");
  res.headers.set(
    "Access-Control-Allow-Methods",
    "GET, POST, PUT, DELETE, OPTIONS"
  );
  res.headers.set(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization"
  );
  return res;
}

export const config = {
  matcher: ["/((?!_next|static|favicon.ico|manifest).*)"],
};
