/**
 * GET /api/agent/agent-insurance
 *
 * AgentInsurancePool — Agent insurance pool for risk management and coverage across the protocol.
 *
 * Query params:
 *   ?chain=base   — chain to query (default: "base")
 *   ?address=0x... — (optional) agent address to query
 *
 * SECURITY: Read-only. No private keys accepted.
 */

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

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 = AGENT_INSURANCE[chain];

  return NextResponse.json({
    chain,
    chainId: CHAIN_IDS[chain],
    contract,
    explorerUrl: `${EXPLORER_URLS[chain]}/address/${contract}`,
    query: address || null,
    contractName: 'AgentInsurancePool',
    description: 'Agent insurance pool for risk management and coverage across the protocol.',
    abi: {
    "deposit": "deposit() payable \u2014 contribute to the pool",
    "withdraw": "withdraw(uint256 amount) \u2014 withdraw from pool",
    "getCoverage": "getCoverage(address agent) \u2192 uint256 \u2014 get agent coverage",
    "getPoolBalance": "getPoolBalance() \u2192 uint256 \u2014 total pool balance"
},
  }, { headers: CORS });
}
