/**
 * GET /api/abis/[name]
 * GET /api/abis/[name]?chain=base
 *
 * Returns a contract ABI as plain JSON — ready to feed into viem, ethers, or wagmi.
 *
 * If ?chain=xxx is passed and a chain-specific override exists (e.g. "BeliefAttestationVerifier_base"),
 * that variant is returned. Otherwise the canonical/shared ABI is returned.
 *
 * Also returns addresses per chain so partners can skip /api/contracts.
 */

import { NextResponse } from 'next/server';
import { ABI_MAP } from '../../../lib/abis/abi-map';
import {
  BASE_CONTRACTS,
  AVALANCHE_CONTRACTS,
  ARBITRUM_CONTRACTS,
  POLYGON_CONTRACTS,
} from '../../../lib/contracts';

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

const VALID_CHAINS = ['base', 'avalanche', 'arbitrum', 'polygon'] as const;

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

export async function GET(
  request: Request,
  { params }: { params: Promise<{ name: string }> | { name: string } }
) {
  const { name } = await params;

  if (!name || !/^[A-Za-z0-9_]+$/.test(name)) {
    return NextResponse.json(
      { error: 'Invalid contract name. Use alphanumeric + underscore.' },
      { status: 400, headers: CORS }
    );
  }

  const url = new URL(request.url);
  const chain = url.searchParams.get('chain');

  if (chain && !VALID_CHAINS.includes(chain as typeof VALID_CHAINS[number])) {
    return NextResponse.json(
      { error: `Invalid chain: "${chain}". Valid: ${VALID_CHAINS.join(', ')}` },
      { status: 400, headers: CORS }
    );
  }

  // Resolve ABI: chain-specific override first, then canonical
  let abi: readonly any[] | undefined;
  let resolvedFrom = name;

  if (chain) {
    const chainKey = `${name}_${chain}`;
    if (ABI_MAP[chainKey]) {
      abi = ABI_MAP[chainKey];
      resolvedFrom = chainKey;
    }
  }
  if (!abi) abi = ABI_MAP[name];

  if (!abi) {
    const available = Object.keys(ABI_MAP)
      .filter(k => !k.includes('_'))
      .sort();
    return NextResponse.json(
      {
        error: `ABI not found: "${name}"`,
        availableABIs: available,
        hint: `Try GET /api/abis for the full list.`,
      },
      { status: 404, headers: CORS }
    );
  }

  // Build address lookup for this contract across chains
  const addresses: Record<string, string> = {};
  const lookup = (chainKey: string, contracts: typeof BASE_CONTRACTS) => {
    const match = contracts.find(c => c.name === name);
    if (match) addresses[chainKey] = match.address;
  };
  lookup('base', BASE_CONTRACTS);
  lookup('avalanche', AVALANCHE_CONTRACTS);
  lookup('arbitrum', ARBITRUM_CONTRACTS);
  lookup('polygon', POLYGON_CONTRACTS);

  const functions = abi.filter((x: any) => x?.type === 'function').map((x: any) => x.name);
  const events = abi.filter((x: any) => x?.type === 'event').map((x: any) => x.name);

  return NextResponse.json({
    name,
    resolvedFrom,
    chain: chain || null,
    addresses,
    functions,
    events,
    abi,
  }, {
    headers: {
      ...CORS,
      'Cache-Control': 'public, max-age=3600',
    },
  });
}
