/**
 * POST /api/x402/actions/bridge-trust-message — $0.40 USDC
 * Calls VaultfireTeleporterBridge.sendReputation(address,uint256,uint256,uint256,uint256)
 * Selector 0xeab5ae91 (verified byte-equal vs canonical hardhat artifact)
 *
 * Cross-chain reputation bridge — sends a reputation snapshot for `agent`
 * (score, weight, nonce, destChainId) through Vaultfire's teleporter.
 */
import { NextRequest, NextResponse } from 'next/server';
import { withX402 } from 'x402-next';
import { facilitator } from '@coinbase/x402';
import { withActionLogging } from '../_lib/log-action';
import {
  CHAIN_IDS, RPC_URLS, EXPLORERS, TELEPORTER_BRIDGE,
  isValidAddress, isValidChain, encodeUint256, encodeAddress, estimateGas, rejectsPrivateKeyShape,
} from '../_lib/tx-encode';

const PAY_TO = '0xfA15Ee28939B222B0448261A22156070f0A7813C';

const handler = async (req: NextRequest) => {
  let body: any;
  try { body = await req.json(); } catch { body = {}; }
  const keyErr = rejectsPrivateKeyShape(body);
  if (keyErr) return NextResponse.json({ error: keyErr }, { status: 400 });

  const { walletAddress, agent, score, weight, nonce, destChainId, chain = 'base' } = body;
  if (!walletAddress || !agent || score === undefined || weight === undefined || nonce === undefined || destChainId === undefined) {
    return NextResponse.json({ error: 'Missing required fields: walletAddress, agent, score, weight, nonce, destChainId' }, { status: 400 });
  }
  if (!isValidAddress(walletAddress)) return NextResponse.json({ error: 'Invalid walletAddress' }, { status: 400 });
  if (!isValidAddress(agent)) return NextResponse.json({ error: 'Invalid agent address' }, { status: 400 });
  if (!isValidChain(chain)) return NextResponse.json({ error: 'Invalid source chain' }, { status: 400 });

  // sendReputation(address,uint256,uint256,uint256,uint256)
  const calldata = '0xeab5ae91'
    + encodeAddress(agent)
    + encodeUint256(BigInt(score))
    + encodeUint256(BigInt(weight))
    + encodeUint256(BigInt(nonce))
    + encodeUint256(BigInt(destChainId));

  const contract = TELEPORTER_BRIDGE[chain];
  const gasEstimate = await estimateGas(RPC_URLS[chain], walletAddress, contract, calldata);

  return NextResponse.json({
    success: true,
    txData: { to: contract, data: calldata, value: '0', chainId: CHAIN_IDS[chain], gasEstimate },
    chain,
    explorer: `${EXPLORERS[chain]}/address/${contract}`,
    message: `Sign to bridge reputation snapshot for ${agent} from ${chain} to chain ${destChainId} via Vaultfire Teleporter. Score=${score}, weight=${weight}, nonce=${nonce}.`,
    securityNote: 'Vaultfire NEVER accepts private keys. Replay-protected by nonce; relayer settles on the destination chain.',
    _x402: { paid: true, price: '$0.40 USDC', service: 'vaultfire-trust', facilitator: 'cdp', pattern: 'tx-prepare (caller signs)' },
  }, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } });
};

export const POST = withX402(withActionLogging(handler, '$0.40', '/actions/bridge-trust-message'), PAY_TO, {
  price: '$0.40', network: 'base',
  config: {
    description: 'Tx-prepare for VaultfireTeleporterBridge.sendReputation() — cross-chain reputation bridge. Returns unsigned transaction; caller signs in wallet.',
    mimeType: 'application/json',
    outputSchema: {
      input: { type: 'http', method: 'POST', discoverable: true,
        bodySchema: {
          type: 'object', required: ['walletAddress', 'agent', 'score', 'weight', 'nonce', 'destChainId'],
          properties: {
            walletAddress: { type: 'string' },
            agent: { type: 'string', description: 'Agent whose reputation is being bridged' },
            score: { type: 'string', description: 'uint256 reputation score' },
            weight: { type: 'string', description: 'uint256 weight' },
            nonce: { type: 'string', description: 'uint256 replay-protection nonce' },
            destChainId: { type: 'string', description: 'Destination chain id (e.g. 8453 base, 43114 avax, 42161 arb, 137 polygon)' },
            chain: { type: 'string', enum: ['base', 'avalanche', 'arbitrum', 'polygon'], description: 'Source chain (default: base)' },
          },
        },
      },
      output: { type: 'object', properties: { success: { type: 'boolean' }, txData: { type: 'object' }, chain: { type: 'string' } } },
    },
  },
}, facilitator);

export async function OPTIONS() {
  return new NextResponse(null, { status: 204, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' } });
}
