import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";

export async function middleware(req: NextRequest) {
  const token = await getToken({ req });
  const { pathname } = req.nextUrl;

  // If no session, send user to sign-in page
  if (!token) {
    return NextResponse.redirect(new URL("/", req.url));
  }

  const userEmail = token.email || "";

  // Internal users (bypass onboarding)
  const isInternal = userEmail.endsWith("@domna.homes");

  // Not onboarded and not internal
  if (token.onboarded === false && pathname !== "/onboarding" && !isInternal) {
    return NextResponse.redirect(new URL("/onboarding", req.url));
  }

  // Already onboarded but tries to go back to onboarding page
  if (token.onboarded === true && pathname === "/onboarding") {
    return NextResponse.redirect(new URL("/home", req.url));
  }

  // If internal, allow access to everything
  if (isInternal) {
    return NextResponse.next();
  }

  // Everything else allowed
  return NextResponse.next();
}

export const config = {
  matcher: [
    // Protect only app’s authenticated areas
    "/home/:path*",
    "/portfolio/:path*",
    "/search/:path*",
    "/addresses/:path*",
    "/due-considerations/:path*",
    "/eco-spreadsheet/:path*",
    "/onboarding", // add onboarding itself
  ],
};
