/**
 * DEV-ONLY: Clerk auth diagnostic endpoint
 * Tests whether currentUser() and auth() work in server context
 * DELETE before production
 */
import { NextResponse } from "next/server";
import { auth, currentUser } from "@clerk/nextjs/server";
import { cookies, headers } from "next/headers";

export const dynamic = "force-dynamic";

export async function GET() {
  if (process.env.NODE_ENV === "production") {
    return NextResponse.json({ error: "Not available" }, { status: 404 });
  }

  try {
    const authState = await auth();
    const user = await currentUser();

    const cookieStore = await cookies();
    const headerStore = await headers();

    const clerkCookies = cookieStore
      .getAll()
      .filter(
        (c) =>
          c.name.includes("clerk") ||
          c.name.includes("__session") ||
          c.name.includes("__client"),
      );

    const clerkHeaders = Object.fromEntries(
      [...headerStore.entries()].filter(
        ([k]) => k.includes("clerk") || k.includes("x-clerk"),
      ),
    );

    return NextResponse.json({
      authState: {
        userId: authState.userId,
        sessionId: authState.sessionId,
        orgId: authState.orgId,
      },
      currentUser: user
        ? {
            id: user.id,
            email: user.emailAddresses[0]?.emailAddress,
            firstName: user.firstName,
          }
        : null,
      clerkCookies: clerkCookies.map((c) => ({
        name: c.name,
        hasValue: !!c.value,
      })),
      clerkHeaders,
    });
  } catch (err) {
    return NextResponse.json(
      {
        error: String(err),
        stack: err instanceof Error ? err.stack : undefined,
      },
      { status: 500 },
    );
  }
}
