/**
 * GET /api/agent/trust?address=0x...&chain=base  — Read ZK trust attestation status
 *
 * VaultfireTrustAttestation — RISC Zero zero-knowledge proofs for
 * privacy-preserving trust verification. Agents can prove trust level
 * without revealing underlying data.
 *
 * SECURITY: Read-only. No private keys accepted.
 */

import { NextRequest, NextResponse } from 'next/server';
import { resolveChain, SUPPORTED_CHAINS } from '../../_lib/resolve-chain';
import { TRUST_ATTESTATION, CHAIN_IDS, RPC_URLS, EXPLORER_URLS, type SupportedChain } from '../../../lib/contracts';
import { checkRateLimit, RATE_LIMIT_GET } from '../../../lib/rate-limit';

const CORS = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' };
export async function OPTIONS() { return new NextResponse(null, { status: 204, headers: CORS }); }

async function rpcCall(rpc: string, to: string, data: string): Promise<string> {
  const res = await fetch(rpc, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_call', params: [{ to, data }, 'latest'] }) });
  const json = await res.json();
  return json.result || '0x0';
}

export async function GET(request: NextRequest) {
  const rl = checkRateLimit(request, RATE_LIMIT_GET);
  if (rl) return rl;

  const params = request.nextUrl.searchParams;
  const chain = resolveChain(params.get('chain')) as SupportedChain;
  const address = params.get('address');

  if (!chain || !SUPPORTED_CHAINS.includes(chain)) {
    return NextResponse.json({ error: `Invalid chain. Use: ${SUPPORTED_CHAINS.join(', ')}` }, { status: 400, headers: CORS });
  }

  const contract = TRUST_ATTESTATION[chain];
  return NextResponse.json({
    chain,
    chainId: CHAIN_IDS[chain],
    contract,
    explorerUrl: `${EXPLORER_URLS[chain]}/address/${contract}`,
    query: address || null,
    abi: {
      verifyAttestation: 'verifyAttestation(address agent, bytes proof) → bool',
      getAttestationCount: 'getAttestationCount(address agent) → uint256',
      submitAttestation: 'submitAttestation(address agent, bytes32 proofHash, bytes proof)',
    },
    description: 'RISC Zero ZK proofs for privacy-preserving trust verification.',
  }, { headers: CORS });
}
