/**
 * GET /api/x402/trust/sla-status?address=0x...&chain=base — $0.02 USDC
 * Calls AgentSLAEnforcer.getAgentPerformance(address)
 * Selector 0x758182e1 (full ABI 100% matched on-chain bytecode).
 *
 * Returns: activeSLAs, totalStaked, totalPenalized, violationCount.
 */
import { NextRequest, NextResponse } from 'next/server';
import { withX402MultiNet } from '../_lib/with-x402-multinet';
import { ethers } from 'ethers';
import { withFailover } from '../../../_lib/rpc-retry';

const ADDRS: Record<string, { address: string; rpc: string; chainId: number; explorer: string }> = {
  base:      { address: '0xc0b7cFF13C7C7f4DAF36A7c67da47B2Cb311335D', rpc: 'https://base-rpc.publicnode.com', chainId: 8453, explorer: 'https://basescan.org' },
  avalanche: { address: '0x6463434322B05bEb806F60161d5023529288aFF9', rpc: 'https://api.avax.network/ext/bc/C/rpc', chainId: 43114, explorer: 'https://snowtrace.io' },
  arbitrum:  { address: '0xF945aA87dB4E1d14aa7d0572501afa166374B776', rpc: 'https://arb1.arbitrum.io/rpc', chainId: 42161, explorer: 'https://arbiscan.io' },
  polygon:   { address: '0x3f385774dba7d067cda7E5190a659029BF8219dB', rpc: 'https://polygon-bor-rpc.publicnode.com', chainId: 137, explorer: 'https://polygonscan.com' },
};

const ABI = [
  'function getAgentPerformance(address agent) view returns (uint256 activeSLAs, uint256 totalStaked, uint256 totalPenalized, uint256 violationCount)',
] as const;

const handler = async (req: NextRequest) => {
  const { searchParams } = req.nextUrl;
  const address = searchParams.get('address');
  const chain = (searchParams.get('chain') || 'base').toLowerCase();
  if (!address) return NextResponse.json({ error: 'address query parameter is required' }, { status: 400 });
  if (!ethers.isAddress(address)) return NextResponse.json({ error: 'Invalid address' }, { status: 400 });
  const cfg = ADDRS[chain];
  if (!cfg) return NextResponse.json({ error: 'Invalid chain. Use base|avalanche|arbitrum|polygon' }, { status: 400 });

  try {
    const r = await withFailover(chain, async (provider) => {
      const c = new ethers.Contract(cfg.address, ABI, provider);
      return await c.getAgentPerformance(address);
    });
    const totalStaked = BigInt(r[1]);
    const totalPenalized = BigInt(r[2]);
    return NextResponse.json({
      address: address.toLowerCase(),
      chain,
      contractAddress: cfg.address,
      activeSLAs: Number(r[0]),
      totalStakedWei: totalStaked.toString(),
      totalStakedEth: ethers.formatEther(totalStaked),
      totalPenalizedWei: totalPenalized.toString(),
      totalPenalizedEth: ethers.formatEther(totalPenalized),
      violationCount: Number(r[3]),
      explorerUrl: `${cfg.explorer}/address/${cfg.address}`,
      _x402: { paid: true, price: '$0.02 USDC', service: 'vaultfire-trust', facilitator: 'cdp' },
    }, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } });
  } catch (e: any) {
    return NextResponse.json({ error: 'Failed to query AgentSLAEnforcer', detail: e?.shortMessage || e?.message || String(e) }, { 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: 'Look up an agent\'s SLA performance via AgentSLAEnforcer.getAgentPerformance() — active SLA count, total staked ETH, total penalized ETH, and lifetime violation count.',
    mimeType: 'application/json',
    outputSchema: {
      type: 'object',
      properties: {
        address: { type: 'string' },
        chain: { type: 'string' },
        contractAddress: { type: 'string' },
        activeSLAs: { type: 'number' },
        totalStakedWei: { type: 'string' },
        totalStakedEth: { type: 'string' },
        totalPenalizedWei: { type: 'string' },
        totalPenalizedEth: { type: 'string' },
        violationCount: { type: 'number' },
        explorerUrl: { type: 'string' },
      },
    }
}) as (req: NextRequest) => Promise<Response>;
