/**
 * GET /api/x402/trust/history
 *
 * x402 payment-gated trust history — $0.02 USDC per query.
 * Returns the trust event history for an agent: registration timestamp,
 * bonds over time, vouches/slashes, and dispute participation.
 *
 * 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 {
    // Parallel: status (registration + bonds), vouching profile, disputes
    const [statusRes, vouchRes] = await Promise.all([
      fetch(`${req.nextUrl.origin}/api/agent/status?address=${encodeURIComponent(address)}&chain=${chain}`, { signal: AbortSignal.timeout(15000) }).then(r => r.json()).catch(() => ({})),
      fetch(`${req.nextUrl.origin}/api/agent/vouching?address=${encodeURIComponent(address)}&chain=${chain}`, { signal: AbortSignal.timeout(15000) }).then(r => r.json()).catch(() => ({})),
    ]);

    const events: Array<{ event: string; timestamp?: number; data: any }> = [];

    if (statusRes?.registered) {
      events.push({
        event: 'identity_registered',
        timestamp: statusRes.registeredAt || null,
        data: { vnsName: statusRes.vnsName, identityType: statusRes.identityType, chain },
      });
    }

    if (Array.isArray(statusRes?.bonds)) {
      for (const b of statusRes.bonds) {
        events.push({
          event: 'bond_active',
          timestamp: b.timestamp || null,
          data: { bondId: b.id, partner: b.partner, stakeEth: b.stakeEth, tier: b.tier },
        });
      }
    }

    const slashCount = parseInt(vouchRes?.profile?.slashCount || '0', 10);
    if (slashCount > 0) {
      events.push({
        event: 'slashes_recorded',
        data: { count: slashCount },
      });
    }

    // Sort newest-first when timestamps available
    events.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));

    return NextResponse.json({
      address,
      chain,
      events,
      summary: {
        registered: !!statusRes?.registered,
        registeredAt: statusRes?.registeredAt || null,
        activeBonds: statusRes?.bondCount || 0,
        vouchesReceived: parseInt(vouchRes?.profile?.totalVouchesReceived || '0', 10),
        slashCount,
        cleanRecord: 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: 'Trust history timeline for an agent — registration, bonds, vouches, and slashes assembled from on-chain state.',
      mimeType: 'application/json',
      outputSchema: {
        type: 'object',
        properties: {
          address: { type: 'string' },
          chain: { type: 'string' },
          events: { type: 'array' },
          summary: { type: 'object' },
        },
      }
}) as (req: NextRequest) => Promise<Response>;
