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

const PROTECTED = ["/books", "/admin-users"];
const AUTH = ["/signin", "/signup"];

export function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;
  const authCookie = req.cookies.get("session")?.value;
  const isAuthed = Boolean(authCookie);

  if (PROTECTED.some((p) => pathname.startsWith(p))) {
    if (!isAuthed) {
      const url = new URL("/signin", req.url);
      url.searchParams.set("from", pathname);
      return NextResponse.redirect(url);
    }
  }

  if (AUTH.includes(pathname) && isAuthed) {
    return NextResponse.redirect(new URL("/books", req.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    "/books/:path*",
    "/admin-users/:path*",
    "/signin",
    "/signup",
  ],
};
