import { NextResponse } from 'next/server';

/**
 * GET /api/protocol/bond-counts
 *
 * Returns the live count of bonds split by contract type, across all chains.
 * Reads `nextBondId()` from each chain's partnership and accountability
 * contracts, sums them, and returns the breakdown.
 *
 * This is the source of truth for "how many of our bonds are partnership
 * vs accountability" — used by /demo so we can show honest, split numbers.
 */

export const dynamic = 'force-dynamic';
export const revalidate = 0;

const CORS_HEADERS = {
  '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_HEADERS });
}

const CHAINS = {
  base: {
    rpcs: ['https://base-rpc.publicnode.com', 'https://mainnet.base.org'],
    partnership: '0x01C479F0c039fEC40c0Cf1c5C921bab457d57441',
    accountability: '0x6750D28865434344e04e1D0a6044394b726C3dfE',
  },
  avalanche: {
    rpcs: ['https://api.avax.network/ext/bc/C/rpc', 'https://avalanche-c-chain-rpc.publicnode.com'],
    partnership: '0xDC8447c66fE9D9c7D54607A98346A15324b7985D',
    accountability: '0x376831fB2457E34559891c32bEb61c442053C066',
  },
  arbitrum: {
    rpcs: ['https://arb1.arbitrum.io/rpc', 'https://arbitrum-one-rpc.publicnode.com'],
    partnership: '0xdB54B8925664816187646174bdBb6Ac658A55a5F',
    accountability: '0xef3A944f4d7bb376699C83A29d7Cb42C90D9B6F0',
  },
  polygon: {
    rpcs: ['https://polygon-bor-rpc.publicnode.com'],
    partnership: '0x83dd216449B3F0574E39043ECFE275946fa492e9',
    accountability: '0xdB54B8925664816187646174bdBb6Ac658A55a5F',
  },
} as const;

const SEL_NEXT_BOND_ID = '0xee53a423'; // nextBondId()

async function rpcCallOne(url: string, to: string, data: string): Promise<string | null> {
  try {
    const res = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_call', params: [{ to, data }, 'latest'] }),
      signal: AbortSignal.timeout(8000),
    });
    const json = await res.json();
    if (json.error || !json.result || json.result === '0x') return null;
    return json.result as string;
  } catch {
    return null;
  }
}

async function rpcCall(rpcs: readonly string[], to: string, data: string): Promise<string | null> {
  for (const url of rpcs) {
    const r = await rpcCallOne(url, to, data);
    if (r) return r;
  }
  return null;
}

/**
 * Returns the count of bonds ever created in this contract.
 *
 * `nextBondId()` returns the *next* ID to be assigned. Bond IDs start at 1,
 * so the count of bonds created so far is `nextBondId - 1`. This matches
 * how /api/hub/stats counts bonds — keeping every surface consistent.
 */
async function getBondCount(rpcs: readonly string[], contract: string): Promise<number> {
  const result = await rpcCall(rpcs, contract, SEL_NEXT_BOND_ID);
  if (!result) return 0;
  try {
    const nextId = parseInt(result.replace('0x', ''), 16);
    return Math.max(0, nextId - 1);
  } catch {
    return 0;
  }
}

export async function GET() {
  const tasks: Promise<{ chain: string; partnership: number; accountability: number }>[] = [];

  for (const [chain, cfg] of Object.entries(CHAINS)) {
    tasks.push(
      Promise.all([
        getBondCount(cfg.rpcs, cfg.partnership),
        getBondCount(cfg.rpcs, cfg.accountability),
      ]).then(([p, a]) => ({ chain, partnership: p, accountability: a })),
    );
  }

  const results = await Promise.all(tasks);

  const partnership = results.reduce((s, r) => s + r.partnership, 0);
  const accountability = results.reduce((s, r) => s + r.accountability, 0);
  const perChain: Record<string, { partnership: number; accountability: number }> = {};
  for (const r of results) {
    perChain[r.chain] = { partnership: r.partnership, accountability: r.accountability };
  }

  return NextResponse.json(
    {
      partnership,
      accountability,
      total: partnership + accountability,
      perChain,
      timestamp: Date.now(),
    },
    { headers: CORS_HEADERS },
  );
}
