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

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Get session token from cookies
  const sessionToken = request.cookies.get("sessionToken")?.value;

  // Protect /main/* routes — redirect to login if no cookie
  if (pathname.startsWith("/main")) {
    if (!sessionToken) {
      return NextResponse.redirect(new URL("/auth/login", request.url));
    }
    return NextResponse.next();
  }

  // Protect /api/* routes (except /api/auth and /api/health)
  if (pathname.startsWith("/api")) {
    if (pathname.startsWith("/api/auth") || pathname.startsWith("/api/health")) {
      return NextResponse.next();
    }

    if (!sessionToken) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    return NextResponse.next();
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/main/:path*", "/api/:path*"],
};
