/**
 * app/onboarding/org/page.js — Create-or-join onboarding (server component).
 *
 * A signed-in Supabase user with no org lands here (via requireOrgOrRedirect)
 * instead of a half-broken page. Two equal-weight choices: Create an org, or
 * Join with an invite. Any pending EMAIL invites for the user's address are
 * surfaced for explicit Accept (Tension-2). If the user already has an org, we
 * bounce them home.
 */

import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import { AdminShell } from '@/app/components/admin/admin-page.jsx';
import { getSession } from '@/lib/auth.js';
import { listPendingEmailInvitesForEmail } from '@/lib/invites.js';
import { PENDING_INVITE_COOKIE } from '@/lib/pending-invite.js';
import OrgOnboardingClient from './onboarding-client.jsx';

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

export const metadata = {
  title: 'Join or create an organization · madarX',
};

export default async function OrgOnboardingPage() {
  const session = await getSession();
  if (!session) redirect('/login?next=/onboarding/org');

  // Link-join completion: a token stashed by /api/auth/join-bootstrap (survives
  // sign-in via httpOnly cookie) is redeemed by join-complete, which clears the
  // cookie either way — so this cannot loop.
  const pendingInvite = (await cookies()).get(PENDING_INVITE_COOKIE)?.value;
  if (pendingInvite) redirect('/api/orgs/join-complete');

  if (session.org_id) redirect('/'); // already in an org

  // Pending email invites are read locally here; in supabase mode the explicit
  // Accept action also runs the cloud claim RPC under the user's own JWT.
  let pending = [];
  try {
    pending = session.email ? listPendingEmailInvitesForEmail(session.email) : [];
  } catch {
    pending = [];
  }

  return (
    <AdminShell
      title="Join or create an organization"
      description="You're signed in but not part of an organization yet."
      hideProjectSwitcher
    >
      <OrgOnboardingClient email={session.email || ''} pendingInvites={pending} />
    </AdminShell>
  );
}
