/**
 * GET /api/x402/trust/vns-resolve
 *
 * x402 payment-gated VNS lookup — $0.01 USDC per query.
 * Resolve a .vns name to an address, OR reverse-resolve an address to its .vns name.
 *
 * Query:
 *   ?name=alice          — forward resolve
 *   ?address=0x...       — reverse resolve
 *   ?chain=base          — chain (default: base)
 *
 * Proxies to the real hub API at /api/agent/vns.
 */

import { NextRequest, NextResponse } from 'next/server';
import { withX402MultiNet } from '../_lib/with-x402-multinet';

const handler = async (req: NextRequest) => {
  const { searchParams } = req.nextUrl;
  const name = searchParams.get('name');
  const address = searchParams.get('address');
  const chain = searchParams.get('chain') || 'base';

  if (!name && !address) {
    return NextResponse.json(
      { error: 'Either name or address query parameter is required' },
      { status: 400 }
    );
  }

  try {
    const params = new URLSearchParams();
    if (name) params.set('name', name);
    if (address) params.set('address', address);
    params.set('chain', chain);
    const hubUrl = `${req.nextUrl.origin}/api/agent/vns?${params.toString()}`;
    const hubRes = await fetch(hubUrl);
    const data = await hubRes.json();

    return NextResponse.json({
      ...data,
      _x402: {
        paid: true,
        price: '$0.01 USDC',
        service: 'vaultfire-trust',
        facilitator: 'cdp',
      },
    }, {
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Cache-Control': 'no-store',
      },
    });
  } catch {
    return NextResponse.json(
      { error: 'Failed to query Vaultfire hub' },
      { status: 502 }
    );
  }
};

// Multi-network paywall: accepts USDC on Base AND Solana mainnet.
// Bazaar discovery picks up both networks from the 402 response's `accepts` array.
export const GET = withX402MultiNet(handler, {
  price: '$0.01',
  description: 'Resolve VNS names to addresses (forward) or addresses to VNS names (reverse) across Base, Arbitrum, and Polygon. Falls back to ERC-8004 identity registry for full coverage.',
      mimeType: 'application/json',
      outputSchema: {
        type: 'object',
        properties: {
          name: { type: 'string', description: 'VNS name (e.g. "alice.vns")' },
          address: { type: 'string', description: 'Resolved wallet address' },
          chain: { type: 'string', description: 'Chain queried' },
          source: { type: 'string', description: 'Resolution source (vns | identity-registry)' },
          explorerUrl: { type: 'string', description: 'Block explorer link' },
        },
      }
}) as (req: NextRequest) => Promise<Response>;
