/**
 * GET /api/agent/adapter?chain=base  — Query the ERC-8004 adapter
 *
 * VaultfireERC8004Adapter — Bridges the Vaultfire protocol with the ERC-8004 standard.
 * Provides a unified interface for identity, reputation, and validation lookups.
 *
 * SECURITY: Read-only. No private keys accepted.
 */

import { NextRequest, NextResponse } from 'next/server';
import { resolveChain, SUPPORTED_CHAINS } from '../../_lib/resolve-chain';
import { ERC8004_ADAPTER, IDENTITY_REGISTRY, REPUTATION_REGISTRY, VALIDATION_REGISTRY, CHAIN_IDS, 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 }); }

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

  const chain = resolveChain(request.nextUrl.searchParams.get('chain')) as SupportedChain;
  if (!chain || !SUPPORTED_CHAINS.includes(chain)) {
    return NextResponse.json({ error: `Invalid chain. Use: ${SUPPORTED_CHAINS.join(', ')}` }, { status: 400, headers: CORS });
  }

  const adapter = ERC8004_ADAPTER[chain];
  return NextResponse.json({
    chain,
    chainId: CHAIN_IDS[chain],
    contract: adapter,
    linkedRegistries: {
      identity: IDENTITY_REGISTRY[chain],
      reputation: REPUTATION_REGISTRY[chain],
      validation: VALIDATION_REGISTRY[chain],
    },
    explorerUrl: `${EXPLORER_URLS[chain]}/address/${adapter}`,
    abi: {
      getFullProfile: 'getFullProfile(address agent) → (bool registered, uint256 reputation, bool validated)',
      getIdentity: 'getIdentity(address agent) → (string name, bytes32 metadataHash, uint256 registeredAt)',
      getReputation: 'getReputation(address agent) → uint256',
      isValidated: 'isValidated(address agent) → bool',
    },
    description: 'Unified ERC-8004 adapter. Single entry point for identity, reputation, and validation lookups.',
  }, { headers: CORS });
}
