/**
 * GET /api/x402/trust/credentials
 *
 * x402 payment-gated credentials — $0.01 USDC per query.
 * Payments routed through CDP facilitator for Bazaar discovery.
 *
 * Capability credentials profile for any AI agent — total credentials, active credentials, task proofs. Reads the on-chain credential registry live.
 *
 * Proxies to the real hub API at /api/agent/credentials.
 */

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');
  if (!address) {
    return NextResponse.json(
      { error: 'address query parameter is required' },
      { status: 400 }
    );
  }
  const chain = searchParams.get('chain') || 'base';

  try {
    const params = new URLSearchParams();
    params.set('address', address);
    params.set('chain', chain);
    const hubUrl = `${req.nextUrl.origin}/api/agent/credentials` + (params.toString() ? `?${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: 'Capability credentials profile for any AI agent — total credentials, active credentials, task proofs. Reads the on-chain credential registry live.',
      mimeType: 'application/json',
      outputSchema: {
        type: 'object',
        properties: {
          address: { type: 'string', description: 'Agent wallet address' },
          chain: { type: 'string', description: 'Chain queried' },
          agentProfile: { type: 'object', description: 'totalCredentials, activeCredentials, totalTaskProofs' },
        },
      }
}) as (req: NextRequest) => Promise<Response>;
