/**
 * GET /api/x402/trust/relationships
 *
 * x402 payment-gated vouching graph slice — $0.02 USDC per query.
 * Returns the vouching relationships for a given agent: who they vouch for,
 * who vouches for them, plus a network summary.
 *
 * Query:
 *   ?address=0x...   — required
 *   ?chain=base      — default base
 */

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 {
    // Pull the agent's vouching profile
    const profileUrl = `${req.nextUrl.origin}/api/agent/vouching?address=${encodeURIComponent(address)}&chain=${encodeURIComponent(chain)}`;
    const profileRes = await fetch(profileUrl, { signal: AbortSignal.timeout(15000) });
    const profile = await profileRes.json();

    // Pull bond partnerships (other agents this one is bonded with)
    const partnersUrl = `${req.nextUrl.origin}/api/agent/partnerships?address=${encodeURIComponent(address)}`;
    const partnersRes = await fetch(partnersUrl, { signal: AbortSignal.timeout(15000) });
    const partners = await partnersRes.json();

    const totalReceived = parseInt(profile?.profile?.totalVouchesReceived || '0', 10);
    const totalGiven = parseInt(profile?.profile?.totalVouchesGiven || '0', 10);
    const stakeReceivedWei = profile?.profile?.totalStakeReceived || '0';
    const stakeGivenWei = profile?.profile?.totalStakeGiven || '0';
    const slashCount = parseInt(profile?.profile?.slashCount || '0', 10);

    // Trust degree: ratio of vouches received vs. slashes (defensive composite)
    const integrity = totalReceived > 0 ? Math.round(((totalReceived - slashCount) / totalReceived) * 100) : 0;

    return NextResponse.json({
      address,
      chain,
      vouching: {
        received: totalReceived,
        given: totalGiven,
        stakeReceivedWei,
        stakeGivenWei,
        slashCount,
        integrityPct: Math.max(0, Math.min(100, integrity)),
      },
      partnerships: {
        bonds: partners?.bonds || [],
        bondCount: partners?.bondCount || 0,
      },
      summary: {
        connections: totalReceived + totalGiven,
        reputationCleanRecord: slashCount === 0,
      },
      _x402: {
        paid: true,
        price: '$0.02 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.02',
  description: 'Vouching graph slice for an agent — counts of vouches given/received, total stake, slash record, bond partnerships, plus an integrity composite.',
      mimeType: 'application/json',
      outputSchema: {
        type: 'object',
        properties: {
          address: { type: 'string' },
          chain: { type: 'string' },
          vouching: { type: 'object' },
          partnerships: { type: 'object' },
          summary: { type: 'object' },
        },
      }
}) as (req: NextRequest) => Promise<Response>;
