import { NextResponse, type NextRequest } from "next/server";
import { updateSession } from "@/lib/supabase/middleware";

const isTeacherEmail = (email: string | null) => {
  if (!email) return false;
  const allowed = (process.env.TEACHER_EMAILS ?? "")
    .split(",")
    .map((value) => value.trim().toLowerCase())
    .filter(Boolean);

  if (allowed.length === 0) return false;
  return allowed.includes(email.toLowerCase());
};

export async function middleware(req: NextRequest) {
  const pathname = req.nextUrl.pathname;
  const { response, isAuthed, userEmail, isConfigured } = await updateSession(req);

  const isProtectedCoursePlayer = pathname.startsWith("/courses/") && pathname.includes("/learn");
  const isProtectedPractice = pathname.startsWith("/practice/");
  const isTeacherRoute = pathname.startsWith("/teacher");

  if (!isConfigured) {
    return response;
  }

  if ((isProtectedCoursePlayer || isProtectedPractice || isTeacherRoute) && !isAuthed) {
    const redirectUrl = req.nextUrl.clone();
    redirectUrl.pathname = "/auth/login";
    redirectUrl.searchParams.set("redirectTo", pathname);
    return NextResponse.redirect(redirectUrl);
  }

  if (isTeacherRoute && !isTeacherEmail(userEmail)) {
    const redirectUrl = req.nextUrl.clone();
    redirectUrl.pathname = "/";
    return NextResponse.redirect(redirectUrl);
  }

  return response;
}

export const config = {
  matcher: ["/courses/:path*", "/practice/:path*", "/teacher/:path*"],
};
