/**
 * GET /api/x402/trust/flourishing-metrics?metricId=0x...&chain=base — $0.02 USDC
 * Calls FlourishingMetricsOracle.getLatestValue(bytes32)
 * Selector 0x73fc67dd (verified byte-equal vs canonical hardhat artifact).
 *
 * Returns the latest oracle-reported value + roundId for a Flourishing Metric.
 */
import { NextRequest, NextResponse } from 'next/server';
import { withX402MultiNet } from '../_lib/with-x402-multinet';
import { ethers } from 'ethers';
import { withFailover } from '../../../_lib/rpc-retry';

const ADDRS: Record<string, { address: string; rpc: string; chainId: number; explorer: string }> = {
  base:      { address: '0xf7B2dC73Ec69528F171F4a0ded62da557866BaA5', rpc: 'https://base-rpc.publicnode.com', chainId: 8453, explorer: 'https://basescan.org' },
  avalanche: { address: '0x1437c4081233A4f0B6907dDf5374Ed610cBD6B25', rpc: 'https://api.avax.network/ext/bc/C/rpc', chainId: 43114, explorer: 'https://snowtrace.io' },
  arbitrum:  { address: '0x54e00081978eE2C8d9Ada8e9975B0Bb543D06A55', rpc: 'https://arb1.arbitrum.io/rpc', chainId: 42161, explorer: 'https://arbiscan.io' },
  polygon:   { address: '0xf92baef9523BC264144F80F9c31D5c5C017c6Da8', rpc: 'https://polygon-bor-rpc.publicnode.com', chainId: 137, explorer: 'https://polygonscan.com' },
};

const ABI = [
  'function getLatestValue(bytes32 metricId) view returns (uint256 value, uint256 roundId)',
] as const;

const isBytes32 = (s: string) => /^0x[a-fA-F0-9]{64}$/.test(s || '');

const handler = async (req: NextRequest) => {
  const { searchParams } = req.nextUrl;
  const metricId = searchParams.get('metricId');
  const chain = (searchParams.get('chain') || 'base').toLowerCase();
  if (!metricId) return NextResponse.json({ error: 'metricId query parameter is required (bytes32 hex)' }, { status: 400 });
  if (!isBytes32(metricId)) return NextResponse.json({ error: 'metricId must be 0x + 64 hex chars (bytes32)' }, { status: 400 });
  const cfg = ADDRS[chain];
  if (!cfg) return NextResponse.json({ error: 'Invalid chain. Use base|avalanche|arbitrum|polygon' }, { status: 400 });

  try {
    const r = await withFailover(chain, async (provider) => {
      const c = new ethers.Contract(cfg.address, ABI, provider);
      return await c.getLatestValue(metricId);
    });
    return NextResponse.json({
      metricId,
      chain,
      contractAddress: cfg.address,
      value: BigInt(r[0]).toString(),
      roundId: BigInt(r[1]).toString(),
      explorerUrl: `${cfg.explorer}/address/${cfg.address}`,
      _x402: { paid: true, price: '$0.02 USDC', service: 'vaultfire-trust', facilitator: 'cdp' },
    }, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } });
  } catch (e: any) {
    return NextResponse.json({ error: 'Failed to query FlourishingMetricsOracle', detail: e?.shortMessage || e?.message || String(e) }, { status: 502 });
  }
};

// Multi-network paywall: accepts USDC on Base AND Solana mainnet.
// Bazaar discovery picks up both networks from the 402 response's `accepts` array.
export const GET = withX402MultiNet(handler, {
  price: '$0.02',
  description: 'Read the latest value + roundId for a Vaultfire Flourishing Metric via FlourishingMetricsOracle.getLatestValue() — the multi-oracle aggregated reading for any registered metricId.',
    mimeType: 'application/json',
    outputSchema: {
      type: 'object',
      properties: {
        metricId: { type: 'string' },
        chain: { type: 'string' },
        contractAddress: { type: 'string' },
        value: { type: 'string' },
        roundId: { type: 'string' },
        explorerUrl: { type: 'string' },
      },
    }
}) as (req: NextRequest) => Promise<Response>;
