import { cookies } from "next/headers";
import { createClient } from "@/lib/supabase/server";
import ClientReadout from "./ClientReadout";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

export default async function AuthDebugPage() {
  const cookieStore = await cookies();
  const allCookies = cookieStore.getAll();
  const sbCookies = allCookies.filter((c) => c.name.startsWith("sb-"));

  let session: any = null;
  let user: any = null;
  let getSessionError: string | null = null;
  let getUserError: string | null = null;

  try {
    const supabase = await createClient();
    const sessRes = await supabase.auth.getSession();
    session = sessRes.data?.session;
    if (sessRes.error) getSessionError = sessRes.error.message;
    const userRes = await supabase.auth.getUser();
    user = userRes.data?.user;
    if (userRes.error) getUserError = userRes.error.message;
  } catch (e: any) {
    getSessionError = e?.message || String(e);
  }

  return (
    <>
    <pre style={{ padding: 20, fontFamily: "monospace", whiteSpace: "pre-wrap", background: "#111", color: "#ddd" }}>
{JSON.stringify(
  {
    note: "Server-side view of auth state for the request that loaded this page.",
    cookies_total: allCookies.length,
    sb_cookies: sbCookies.map((c) => ({ name: c.name, value_prefix: c.value.slice(0, 40) + (c.value.length > 40 ? "…" : "") })),
    other_cookie_names: allCookies.filter((c) => !c.name.startsWith("sb-")).map((c) => c.name),
    auth_getSession_error: getSessionError,
    auth_getUser_error: getUserError,
    has_session: !!session,
    session: session
      ? {
          access_token_len: session.access_token?.length,
          refresh_token_len: session.refresh_token?.length,
          expires_in: session.expires_in,
          expires_at: session.expires_at,
          token_type: session.token_type,
          user_id: session.user?.id,
          user_email: session.user?.email,
        }
      : null,
    user: user
      ? {
          id: user.id,
          email: user.email,
          aud: user.aud,
          role: user.role,
        }
      : null,
  },
  null,
  2,
)}
    </pre>
    <ClientReadout />
    </>
  );
}
