import { getAuth } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";

export const runtime = "nodejs";

export async function GET(req: NextRequest) {
  try {
    const auth = await getAuth();
    const response = await auth.handler(req);
    
    const redirectUrl = req.nextUrl.searchParams.get("redirect") || "/account/webinars";
    
    if (response.status >= 300 && response.status < 400) {
      const location = response.headers.get("location");
      if (location) {
        return NextResponse.redirect(new URL(`/auth-callback?redirect=${encodeURIComponent(redirectUrl)}`, req.url));
      }
    }
    
    return response;
  } catch (error) {
    console.error("Discord callback error:", error);
    return new Response("Authentication failed", { status: 500 });
  }
}
