/**
 * GET /api/x402/trust/multi-chain-status
 *
 * x402 payment-gated cross-chain status — $0.03 USDC per query.
 * Returns an agent's trust profile across ALL 4 chains in a single call.
 *
 * Query:
 *   ?address=0x...   — required
 *
 * Proxies to /api/agent/status on each chain in parallel.
 */

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

const CHAINS = ['base', 'avalanche', 'arbitrum', 'polygon'] as const;

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 }
    );
  }

  try {
    const results = await Promise.all(
      CHAINS.map(async (chain) => {
        try {
          const hubUrl = `${req.nextUrl.origin}/api/agent/status?address=${encodeURIComponent(address)}&chain=${chain}`;
          const r = await fetch(hubUrl, { signal: AbortSignal.timeout(15000) });
          const data = await r.json();
          return { chain, ...data };
        } catch (e) {
          return { chain, error: 'unreachable' };
        }
      })
    );

    // Compute aggregate summary
    const registered = results.filter((r: any) => r?.registered).length;
    const totalBonds = results.reduce((sum: number, r: any) => sum + (r?.bondCount || 0), 0);
    const trustScores = results.map((r: any) => r?.trustScore || 0).filter((s) => s > 0);
    const avgTrustScore = trustScores.length ? Math.round(trustScores.reduce((a, b) => a + b, 0) / trustScores.length) : 0;

    return NextResponse.json({
      address,
      summary: {
        chainsRegistered: registered,
        chainsTotal: 4,
        totalActiveBonds: totalBonds,
        avgTrustScore,
        omnichain: registered === 4,
      },
      perChain: results,
      _x402: {
        paid: true,
        price: '$0.03 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.03',
  description: 'Aggregate an agent\'s on-chain status across all 4 chains (Base, Avalanche, Arbitrum, Polygon) in a single call. Returns per-chain registration, bonds, trust score, plus omnichain summary.',
      mimeType: 'application/json',
      outputSchema: {
        type: 'object',
        properties: {
          address: { type: 'string' },
          summary: {
            type: 'object',
            properties: {
              chainsRegistered: { type: 'number' },
              chainsTotal: { type: 'number' },
              totalActiveBonds: { type: 'number' },
              avgTrustScore: { type: 'number' },
              omnichain: { type: 'boolean' },
            },
          },
          perChain: { type: 'array' },
        },
      }
}) as (req: NextRequest) => Promise<Response>;
