import { NextResponse } from "next/server";
import { cookies } from "next/headers";

import { getCookie, hasCookie } from "cookies-next";

export async function middleware(req, next) {
  const token = getCookie("cmc-token", { req }); // Access the token from cookies

  const headers = new Headers(req.headers);
  headers.set("X-XSS-Protection", "1; mode=block");
  headers.set("X-Frame-Options", "SAMEORIGIN");
  headers.set("Content-Security-Policy", "frame-ancestors 'same';");

  const { origin, pathname } = req.nextUrl;

  try {
    // console.log("Test path", pathname, origin);
    if (token) {
      // Redirect to the home page if already authenticated
      NextResponse.redirect(new URL(pathname, origin), { status: 302 });
      // Continue with the request if authenticated
      return NextResponse.next();
    }

    if (
      !authenticationPages.includes(pathname) ||
      (authenticationPages.includes(pathname) && !token)
    ) {
      // Redirect to the login page if not authenticated
      return NextResponse.redirect(new URL("/auth/login", origin), {
        status: 307,
      });
    }

  } catch (error) {
    console.error("Error during authentication check:", error);
    return NextResponse.error();
  }
}

export const config = {
  matcher: "/",
};

const authenticationPages = [
  "/auth/login",
  "/auth/sign-up",
  "/auth/logout",
];
