/**
 * GET /api/x402/trust/protocol-stats
 *
 * x402 payment-gated protocol statistics — $0.01 USDC per query.
 * Payments routed through CDP facilitator for Bazaar discovery.
 *
 * Returns protocol-wide stats:
 *   - Total registered identities
 *   - Active bond count
 *   - Per-chain breakdown
 *   - Locked value per chain
 *
 * Proxies to the real hub API at /api/hub/stats.
 */

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

const handler = async (req: NextRequest) => {
  try {
    const hubUrl = `${req.nextUrl.origin}/api/hub/stats`;
    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: 'Vaultfire — the trust layer for the agentic web. 72 x402 endpoints on Base for AI agent identity (ERC-8004), accountability bonds, on-chain reputation, and Chainlink oracle data. — This endpoint: protocol-wide stats (total registered agents, active bonds, per-chain breakdown across Base, Avalanche, Arbitrum, and Polygon, and locked value). Live snapshot from on-chain queries.',
      mimeType: 'application/json',
      outputSchema: {
        type: 'object',
        properties: {
          totalIdentities: { type: 'number', description: 'Total registered agent identities' },
          activeBonds: { type: 'number', description: 'Total active trust bonds' },
          totalContracts: { type: 'number', description: 'Total deployed smart contracts' },
          chainCounts: {
            type: 'object',
            description: 'Agent count per chain',
            properties: {
              base: { type: 'number' },
              avalanche: { type: 'number' },
              arbitrum: { type: 'number' },
              polygon: { type: 'number' },
            },
          },
        },
      }
}) as (req: NextRequest) => Promise<Response>;
