/**
 * GET /api/x402/trust/agent-status?address=0x...&chain=base
 *
 * x402 payment-gated trust lookup — $0.01 USDC per query.
 * Payments routed through CDP facilitator for Bazaar discovery.
 *
 * Returns the full on-chain trust profile for any AI agent:
 *   - ERC-8004 identity registration status
 *   - Active bond count and locked value
 *   - Trust score (0–95)
 *   - VNS name
 *   - Explorer link
 *
 * Proxies to the real hub API at /api/agent/status.
 */

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

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

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

  try {
    const hubUrl = `${req.nextUrl.origin}/api/agent/status?address=${encodeURIComponent(address)}&chain=${encodeURIComponent(chain)}`;
    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: 'Look up any AI agent\'s on-chain trust profile — ERC-8004 registration, bond count, trust score (0–95), VNS name, and explorer link. Queries real smart contracts across 4 chains.',
  mimeType: 'application/json',
  outputSchema: {
    type: 'object',
    properties: {
      address: { type: 'string', description: 'Agent wallet address' },
      chain: { type: 'string', description: 'Chain queried' },
      registered: { type: 'boolean', description: 'ERC-8004 registration status' },
      vnsName: { type: 'string', description: 'Vaultfire Name Service name' },
      identityType: { type: 'string', description: 'Identity type (agent/human)' },
      hasBond: { type: 'boolean', description: 'Whether agent has active bond' },
      bondCount: { type: 'number', description: 'Number of active bonds' },
      trustScore: { type: 'number', description: 'Trust score 0–95' },
      explorerUrl: { type: 'string', description: 'Block explorer link' },
    },
  },
}) as (req: NextRequest) => Promise<Response>;
