import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import {
  GUEST_SESSION_COOKIE_NAME,
  GUEST_SESSION_MAX_AGE_SECONDS,
} from "@/lib/session/constants";

const isProtectedRoute = createRouteMatcher(["/account(.*)", "/checkout(.*)"]);

export default clerkMiddleware(async (auth, req) => {
  if (isProtectedRoute(req)) await auth.protect();

  const response = NextResponse.next();
  const existing = req.cookies.get(GUEST_SESSION_COOKIE_NAME)?.value;
  if (!existing?.trim()) {
    const sessionId = crypto.randomUUID();
    response.cookies.set(GUEST_SESSION_COOKIE_NAME, sessionId, {
      path: "/",
      maxAge: GUEST_SESSION_MAX_AGE_SECONDS,
      sameSite: "lax",
      secure: process.env.NODE_ENV === "production",
    });
  }
  return response;
});

export const config = {
  matcher: [
    "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
    "/(api|trpc)(.*)",
  ],
};
