/**
 * POST /api/x402/actions/submit-validation — $0.25 USDC
 * Calls ERC8004ValidationRegistry.submitValidation(uint256 requestId, bool approved, string evidenceURI, bytes zkProof) [payable]
 * Selector 0x0ad8d646
 */
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, VALIDATION_REGISTRY, SUPPORTED_CHAINS,
  isValidAddress, isValidChain, encodeUint256, encodeBool, encodeString, encodeDynamicBytes,
  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, requestId, approved, evidenceURI, zkProof = '0x', valueWei = '0', chain = 'base' } = body;
  if (!walletAddress || requestId === undefined || approved === undefined || !evidenceURI) {
    return NextResponse.json({ error: 'Missing: walletAddress, requestId, approved, evidenceURI' }, { status: 400 });
  }
  if (!isValidAddress(walletAddress)) return NextResponse.json({ error: 'Invalid walletAddress' }, { status: 400 });
  if (!isValidChain(chain)) return NextResponse.json({ error: 'Invalid chain' }, { status: 400 });

  // submitValidation(uint256, bool, string, bytes)
  // head = uint256(32) + bool(32) + offset_string(32) + offset_bytes(32) = 0x80
  // string at 0x80; bytes at 0x80 + sizeof(string)
  const evidenceEncoded = encodeString(String(evidenceURI));
  const evidenceTotal = evidenceEncoded.length / 2; // bytes
  const offset_bytes = 0x80 + evidenceTotal;
  const proofClean = String(zkProof).replace(/^0x/, '');
  const proofEncoded = encodeDynamicBytes('0x' + proofClean);

  const calldata = '0x0ad8d646'
    + encodeUint256(BigInt(requestId))
    + encodeBool(Boolean(approved))
    + encodeUint256(0x80)
    + encodeUint256(offset_bytes)
    + evidenceEncoded
    + proofEncoded;

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

  return NextResponse.json({
    success: true,
    txData: { to: contract, data: calldata, value: valueWei, chainId: CHAIN_IDS[chain], gasEstimate },
    chain, explorer: `${EXPLORERS[chain]}/address/${contract}`,
    message: `Sign to submit validation for request #${requestId} on ${chain} (approved: ${approved}).`,
    securityNote: 'Vaultfire NEVER accepts private keys. Caller must be a staked validator.',
    _x402: { paid: true, price: '$0.25 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.25', '/actions/submit-validation'), PAY_TO, {
  price: '$0.25', network: 'base',
  config: {
    description: 'Submit a validation result on the ERC-8004 Validation Registry as a staked validator. Pay $0.25 USDC, sign in your wallet — must already be staked via stakeAsValidator. Includes optional zk proof bytes.',
    mimeType: 'application/json',
    outputSchema: {
      input: { type: 'http', method: 'POST', discoverable: true,
        bodySchema: {
          type: 'object', required: ['walletAddress', 'requestId', 'approved', 'evidenceURI'],
          properties: {
            walletAddress: { type: 'string' }, requestId: { type: 'string' },
            approved: { type: 'boolean' }, evidenceURI: { type: 'string' },
            zkProof: { type: 'string', description: 'hex (0x optional)' },
            valueWei: { type: 'string' },
            chain: { type: 'string', enum: ['base', 'avalanche', 'arbitrum', 'polygon'] },
          },
        },
      },
      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' } });
}
