/**
 * GET /api/orgs/join-complete — finish a link-join after Supabase sign-in.
 *
 * Reads the bearer token stashed by /api/auth/join-bootstrap from the httpOnly
 * pending-invite cookie, redeems it under the now-authenticated session, clears
 * the cookie, and redirects home. This is the robust replacement for the old
 * sessionStorage carry, which silently failed on any login provider hop or
 * new-tab sign-in (the token never survived the redirect).
 *
 * Redemption mirrors POST /api/orgs/join:
 *   • supabase member → redeem_invite_token() RPC under the member's own JWT.
 *   • local mode      → lib/invites.redeemInvite against local SQLite.
 *
 * The token is consumed exactly once; the cookie is always cleared so a failed
 * redeem cannot loop. GET is safe here because the token is a single-use bearer
 * secret already scoped to this browser — no CSRF state-change beyond the join
 * the user explicitly initiated.
 */

import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { requireSession, getAuthMode } from '@/lib/auth.js';
import { redeemInvite } from '@/lib/invites.js';
import { PENDING_INVITE_COOKIE } from '@/lib/pending-invite.js';

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

function _redirect(req, path) {
  const res = NextResponse.redirect(new URL(path, req.url));
  // Always clear the pending cookie on the way out.
  res.cookies.set(PENDING_INVITE_COOKIE, '', { path: '/', maxAge: 0 });
  return res;
}

export async function GET(req) {
  const jar = await cookies();
  const token = jar.get(PENDING_INVITE_COOKIE)?.value || '';

  let session;
  try {
    session = await requireSession(req);
  } catch {
    // Not signed in yet — send them through sign-in, then back here.
    return NextResponse.redirect(new URL('/login?next=/api/orgs/join-complete', req.url));
  }

  if (!token) {
    // Nothing pending — just go home (or to onboarding if they have no org).
    return _redirect(req, session.org_id ? '/' : '/onboarding/org');
  }

  try {
    if (getAuthMode() === 'supabase' && session.supabase_access_token) {
      const { redeemInviteViaCloud } = await import('@/lib/shared-cloud.js');
      await redeemInviteViaCloud(token, session);
    } else {
      redeemInvite(token, session.user_id);
    }
    return _redirect(req, '/?joined=1');
  } catch (err) {
    console.warn('[join-complete] redeem failed:', err?.code || err?.message);
    return _redirect(req, '/onboarding/org?invite_error=1');
  }
}
