/**
 * GET /api/x402/trust/governance-proposals?txId=N&chain=base — $0.02 USDC
 * Calls MultisigGovernance.getTransaction(uint256)
 * Selector 0x33ea3dc8 (verified byte-equal vs canonical hardhat artifact).
 */
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: '0x34a19C7298aCA59e185F1ecfB352AC566bB4B4A9', rpc: 'https://base-rpc.publicnode.com', chainId: 8453, explorer: 'https://basescan.org' },
  avalanche: { address: '0x3ceA2B0853B76Ac75603C1fa2A29D96A4467Bb79', rpc: 'https://api.avax.network/ext/bc/C/rpc', chainId: 43114, explorer: 'https://snowtrace.io' },
  arbitrum:  { address: '0x94F54c849692Cc64C35468D0A87D2Ab9D7Cb6Fb2', rpc: 'https://arb1.arbitrum.io/rpc', chainId: 42161, explorer: 'https://arbiscan.io' },
  polygon:   { address: '0x5DB1B4b412b80d03819395794fCcF5A73BF30656', rpc: 'https://polygon-bor-rpc.publicnode.com', chainId: 137, explorer: 'https://polygonscan.com' },
};

const ABI = [
  'function getTransaction(uint256 txId) view returns (address target, uint256 value, bytes data, bool executed, uint256 numConfirmations, uint256 expiresAt)',
] as const;

const handler = async (req: NextRequest) => {
  const { searchParams } = req.nextUrl;
  const txIdRaw = searchParams.get('txId');
  const chain = (searchParams.get('chain') || 'base').toLowerCase();
  if (txIdRaw === null) return NextResponse.json({ error: 'txId query parameter is required' }, { status: 400 });
  let txId: bigint;
  try { txId = BigInt(txIdRaw); } catch { return NextResponse.json({ error: 'txId must be a non-negative integer' }, { status: 400 }); }
  if (txId < 0n) return NextResponse.json({ error: 'txId must be ≥ 0' }, { 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.getTransaction(txId);
    });
    return NextResponse.json({
      txId: txId.toString(),
      chain,
      contractAddress: cfg.address,
      target: String(r[0]).toLowerCase(),
      valueWei: BigInt(r[1]).toString(),
      valueEth: ethers.formatEther(BigInt(r[1])),
      data: String(r[2]),
      executed: Boolean(r[3]),
      numConfirmations: Number(r[4]),
      expiresAt: Number(r[5]),
      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 MultisigGovernance', 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: 'Inspect a Vaultfire MultisigGovernance proposal via getTransaction(txId) — target, value, calldata, execution status, confirmation count, and expiry.',
    mimeType: 'application/json',
    outputSchema: {
      type: 'object',
      properties: {
        txId: { type: 'string' },
        chain: { type: 'string' },
        contractAddress: { type: 'string' },
        target: { type: 'string' },
        valueWei: { type: 'string' },
        valueEth: { type: 'string' },
        data: { type: 'string' },
        executed: { type: 'boolean' },
        numConfirmations: { type: 'number' },
        expiresAt: { type: 'number' },
        explorerUrl: { type: 'string' },
      },
    }
}) as (req: NextRequest) => Promise<Response>;
