/**
 * GET /api/contracts
 *
 * Return all Vaultfire Protocol contract addresses across all 4 mainnet chains.
 * 134 contracts total: Base (36), Avalanche (32), Arbitrum (33), Polygon (33).
 *
 * Contract names match the canonical names used in contracts.ts and on-chain deployments.
 */

import { NextResponse } from 'next/server';
import { BASE_CONTRACTS, AVALANCHE_CONTRACTS, ARBITRUM_CONTRACTS, POLYGON_CONTRACTS, CHAINS } from '../../lib/contracts';

/* ── CORS headers ── */
const CORS_HEADERS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type',
};

// Payload is static data computed at module load (addresses only change on
// redeploy). Allow clients + CDN to cache for 5 minutes with stale-while-revalidate.
const CACHE_HEADERS = {
  'Cache-Control': 'public, max-age=300, s-maxage=300, stale-while-revalidate=60',
};

export async function OPTIONS() {
  return new NextResponse(null, { status: 204, headers: CORS_HEADERS });
}

function buildChainEntry(
  chain: 'base' | 'avalanche' | 'arbitrum' | 'polygon',
  contracts: { name: string; address: string }[],
) {
  const config = CHAINS[chain];
  const contractMap: Record<string, string> = {};
  for (const c of contracts) {
    contractMap[c.name] = c.address;
  }
  return {
    chainId: config.id,
    rpc: config.rpcUrls.default.http[0],
    explorer: config.explorerUrl,
    contracts: contractMap,
  };
}

const CONTRACTS = {
  base: buildChainEntry('base', BASE_CONTRACTS),
  avalanche: buildChainEntry('avalanche', AVALANCHE_CONTRACTS),
  arbitrum: buildChainEntry('arbitrum', ARBITRUM_CONTRACTS),
  polygon: buildChainEntry('polygon', POLYGON_CONTRACTS),
};

// Compute total dynamically from actual data
const TOTAL = BASE_CONTRACTS.length + AVALANCHE_CONTRACTS.length + ARBITRUM_CONTRACTS.length + POLYGON_CONTRACTS.length;

export async function GET() {
  return NextResponse.json({
    totalContracts: TOTAL,
    chains: ['base', 'avalanche', 'arbitrum', 'polygon'],
    chainBreakdown: {
      base: BASE_CONTRACTS.length,
      avalanche: AVALANCHE_CONTRACTS.length,
      arbitrum: ARBITRUM_CONTRACTS.length,
      polygon: POLYGON_CONTRACTS.length,
    },
    ...CONTRACTS,
    verifiedSelectors: {
      'registerAgent(string,string,bytes32)': '0x2b3ce0bf',
      'createBond(address,string)': '0x7ac5113b',
      'grantConsent(bytes32)': '0x1c9df7ef',
      'getTotalAgents()': '0x3731a16f',
      'getAgent(address)': '0xfb3551ff',
    },
  }, { headers: { ...CORS_HEADERS, ...CACHE_HEADERS } });
}
