/**
 * POST /api/x402/actions/create-partnership-bond — $0.50 USDC
 *
 * Returns an unsigned PAYABLE transaction calling AIPartnershipBondsV2.createBond(address aiAgent, string partnershipType).
 * Caller signs with their own wallet — no private keys handled server-side.
 */

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, PARTNERSHIP_BONDS, SUPPORTED_CHAINS,
  isValidAddress, isValidChain, encodeUint256, encodeAddress, encodeString,
  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, aiAgent, partnershipType, stakeWei = '10000000000000000', chain = 'base' } = body;
  if (!walletAddress || !aiAgent || !partnershipType) {
    return NextResponse.json({ error: 'Missing required: walletAddress, aiAgent, partnershipType' }, { status: 400 });
  }
  if (!isValidAddress(walletAddress) || !isValidAddress(aiAgent)) {
    return NextResponse.json({ error: 'Invalid address' }, { status: 400 });
  }
  if (!isValidChain(chain)) {
    return NextResponse.json({ error: `Invalid chain. Use: ${SUPPORTED_CHAINS.join(', ')}` }, { status: 400 });
  }

  // createBond(address,string) selector 0x7ac5113b
  // params: address (32 bytes), offset to string (0x40), string-length, string-data
  const ptype = String(partnershipType);
  const calldata = '0x7ac5113b'
    + encodeAddress(aiAgent)
    + encodeUint256(0x40)
    + encodeString(ptype);

  const contract = PARTNERSHIP_BONDS[chain];
  const valueHex = '0x' + BigInt(stakeWei).toString(16);
  const gasEstimate = await estimateGas(RPC_URLS[chain], walletAddress, contract, calldata, valueHex);

  return NextResponse.json({
    success: true,
    txData: { to: contract, data: calldata, value: stakeWei, chainId: CHAIN_IDS[chain], gasEstimate },
    chain,
    explorer: `${EXPLORERS[chain]}/address/${contract}`,
    message: `Sign in your wallet (${walletAddress}) to create a partnership bond with ${aiAgent} on ${chain}. Stake: ${stakeWei} wei.`,
    securityNote: 'Vaultfire NEVER accepts private keys. Sign locally in your Base App / MetaMask / WalletConnect.',
    _x402: { paid: true, price: '$0.50 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.50', '/actions/create-partnership-bond'), PAY_TO, {
  price: '$0.50',
  network: 'base',
  config: {
    description: 'Vaultfire — accountability bonds for AI agents that reward flourishing, not fear. Agents stake ETH and earn distribution when on-chain Flourishing Metrics (human growth, autonomy, dignity, tasks mastered, creativity) show real human↔agent impact. Morals over metrics, on-chain. — This endpoint: create an AI partnership bond on AIPartnershipBondsV2. Pay $0.50 USDC, receive an unsigned payable tx with your stake, sign locally in your wallet. No private keys handled server-side.',
    mimeType: 'application/json',
    outputSchema: {
      input: {
        type: 'http', method: 'POST', discoverable: true,
        bodySchema: {
          type: 'object',
          required: ['walletAddress', 'aiAgent', 'partnershipType'],
          properties: {
            walletAddress: { type: 'string', description: 'Human partner wallet that signs and stakes' },
            aiAgent: { type: 'string', description: 'AI agent address bonded to' },
            partnershipType: { type: 'string', description: 'Free-form partnership descriptor' },
            stakeWei: { type: 'string', description: 'Wei to stake (default 0.01 ETH)' },
            chain: { type: 'string', enum: ['base', 'avalanche', 'arbitrum', 'polygon'] },
          },
        },
      },
      output: {
        type: 'object',
        properties: {
          success: { type: 'boolean' }, txData: { type: 'object' }, chain: { type: 'string' },
          explorer: { type: 'string' }, message: { 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',
  }});
}
