import { NextRequest, NextResponse } from 'next/server';
import { apiUrl } from '@/lib/api-base';

export async function GET(req: NextRequest) {
  const name = req.nextUrl.searchParams.get('name');
  const upstream = new URL(apiUrl('/nip05'));
  if (name) upstream.searchParams.set('name', name);

  try {
    const res = await fetch(upstream.toString(), { cache: 'no-store' });
    if (!res.ok) {
      return NextResponse.json(
        {},
        {
          status: 502,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Cache-Control': 'no-store',
          },
        }
      );
    }
    const data = await res.json();
    return NextResponse.json(data, {
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Cache-Control': 'no-store',
      },
    });
  } catch (err) {
    console.error('NIP-05 proxy error:', err);
    return NextResponse.json(
      {},
      {
        status: 502,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Cache-Control': 'no-store',
        },
      }
    );
  }
}
