/**
 * Proxy OAuth login to platform-service.
 * POST /api/auth/oauth/:provider { idToken }
 * Returns either { accessToken, refreshToken, user } or { mfaRequired, mfaChallenge, methods }.
 */

import { NextRequest, NextResponse } from 'next/server';
import { getRequestProductId } from '@/lib/product-config';

const PLATFORM_API = process.env.PLATFORM_SERVICE_URL || 'http://localhost:4003';

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ provider: string }> }
) {
  try {
    const { provider } = await params;
    const { idToken } = await req.json();

    if (!idToken) {
      return NextResponse.json({ error: 'idToken required' }, { status: 400 });
    }

    const res = await fetch(`${PLATFORM_API}/api/auth/oauth/${provider}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ idToken, productId: getRequestProductId(req) }),
    });

    const data = await res.json();
    if (!res.ok) {
      return NextResponse.json(
        { error: data.error || `OAuth ${provider} login failed` },
        { status: res.status }
      );
    }

    return NextResponse.json(data);
  } catch {
    return NextResponse.json({ error: 'Platform service unavailable' }, { status: 502 });
  }
}
