import { NextResponse } from 'next/server';

function env(name: string): string | undefined {
  const v = process.env[name];
  return typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined;
}

/** Verify a Keycloak access token for Sankofa Studio portal-exchange / OIDC completion. */
export async function POST(req: Request) {
  const body = (await req.json().catch(() => ({}))) as { token?: string };
  const headerToken = req.headers.get('authorization')?.replace(/^Bearer\s+/i, '').trim();
  const token = (body.token || headerToken || '').trim();
  if (!token) {
    return NextResponse.json({ valid: false, detail: 'missing token' }, { status: 400 });
  }

  const keycloakUrl = env('KEYCLOAK_URL');
  const realm = env('KEYCLOAK_REALM') || 'master';
  if (!keycloakUrl) {
    return NextResponse.json({ valid: false, detail: 'KEYCLOAK_URL not configured' }, { status: 503 });
  }

  const userinfoUrl = `${keycloakUrl.replace(/\/$/, '')}/realms/${realm}/protocol/openid-connect/userinfo`;
  const userResp = await fetch(userinfoUrl, {
    headers: { Authorization: `Bearer ${token}` },
    cache: 'no-store',
  });
  if (!userResp.ok) {
    return NextResponse.json({ valid: false, detail: 'invalid token' }, { status: 401 });
  }

  const user = (await userResp.json()) as { email?: string; sub?: string; preferred_username?: string };
  const studioApiKey = env('STUDIO_SHARED_API_KEY') || env('FUSIONAI_API_KEY');
  if (!studioApiKey) {
    return NextResponse.json({ valid: false, detail: 'STUDIO_SHARED_API_KEY not configured' }, { status: 503 });
  }

  return NextResponse.json({
    valid: true,
    authenticated: true,
    email: user.email || user.preferred_username || user.sub,
    studio_api_key: studioApiKey,
    api_key: studioApiKey,
  });
}
