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

// Lightweight session check for Edge Runtime middleware.
// We can't use 'jsonwebtoken' here because it relies on Node.js crypto APIs
// (crypto.createHmac) that aren't available in the Edge Runtime (V8 isolates).
// 'jose' uses Web Crypto APIs which work in both Edge and Node runtimes.
const JWT_SECRET = new TextEncoder().encode(
  process.env.JWT_SECRET || "dev-secret-change-in-production-please"
);
const SESSION_COOKIE = "sb_session";

interface SessionPayload {
  userId: string;
  email: string;
  role: "admin" | "client";
}

async function verifyToken(token: string): Promise<SessionPayload | null> {
  try {
    const { payload } = await jwtVerify(token, JWT_SECRET);
    return payload as unknown as SessionPayload;
  } catch {
    return null;
  }
}

// Middleware: protects /admin routes (admin-only) and client portal routes.
// JWT is verified from the cookie. If the token is invalid or the role doesn't match,
// redirect to /login.
export async function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;
  const token = req.cookies.get(SESSION_COOKIE)?.value || "";

  // /admin/* requires admin role
  if (pathname === "/admin" || pathname.startsWith("/admin/")) {
    const session = await verifyToken(token);
    if (!session) {
      const url = req.nextUrl.clone();
      url.pathname = "/login";
      url.searchParams.set("redirect", pathname);
      return NextResponse.redirect(url);
    }
    if (session.role !== "admin") {
      // Clients trying to access /admin get redirected to their dashboard
      const url = req.nextUrl.clone();
      url.pathname = "/dashboard";
      return NextResponse.redirect(url);
    }
  }

  // /dashboard requires any authenticated user
  if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) {
    const session = await verifyToken(token);
    if (!session) {
      const url = req.nextUrl.clone();
      url.pathname = "/login";
      url.searchParams.set("redirect", pathname);
      return NextResponse.redirect(url);
    }
  }

  return NextResponse.next();
}

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