/**
 * GET  /api/orgs/invites/pending — list pending EMAIL invites for the signed-in
 *      user's address (across orgs). Surfaced on /onboarding/org so a member can
 *      accept explicitly (Tension-2: no auto-claim-on-every-request).
 * POST /api/orgs/invites/pending — accept: claim all pending email invites for
 *      the verified address now. Returns the org(s) joined.
 */

import { requireSession, getAuthMode } from '@/lib/auth.js';
import { listPendingEmailInvitesForEmail, claimEmailInvites } from '@/lib/invites.js';

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

export async function GET(req) {
  try {
    const session = await requireSession(req);
    if (!session.email) return Response.json({ pending: [] });
    return Response.json({ pending: listPendingEmailInvitesForEmail(session.email) });
  } catch (err) {
    if (err.status) return Response.json({ error: err.error }, { status: err.status });
    console.error('GET /api/orgs/invites/pending error:', err);
    return Response.json({ error: 'Failed to list pending invites' }, { status: 500 });
  }
}

export async function POST(req) {
  try {
    const session = await requireSession(req);
    if (!session.email) return Response.json({ error: 'no_email' }, { status: 400 });

    let claimed = [];
    if (getAuthMode() === 'supabase' && session.supabase_access_token) {
      // Cloud claim under the member's own JWT (verified email enforced server-side).
      const { claimEmailInvitesViaCloud } = await import('@/lib/shared-cloud.js');
      claimed = await claimEmailInvitesViaCloud(session);
      if (!claimed.length) claimed = claimEmailInvites(session.user_id, session.email);
    } else {
      claimed = claimEmailInvites(session.user_id, session.email);
    }

    if (!claimed.length) return Response.json({ error: 'no_pending_invite' }, { status: 404 });
    return Response.json({ ok: true, joined: claimed });
  } catch (err) {
    if (err.status) return Response.json({ error: err.error }, { status: err.status });
    console.error('POST /api/orgs/invites/pending error:', err);
    return Response.json({ error: 'Failed to accept invite' }, { status: 500 });
  }
}
