/**
 * POST /api/x402/actions/create-vkp-vault — $0.40 USDC
 * Calls VKPFactory.createVault(uint256,uint256,uint256,uint256)
 * Selector 0xcb0354f0 (verified vs viem.toFunctionSelector + on-chain dispatcher)
 *
 * Creates a Vaultfire Knowledge Protocol vault for the caller — a personal,
 * sovereign smart vault for storing knowledge attestations and routing fees.
 */
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, VKP_FACTORY,
  isValidAddress, isValidChain, encodeUint256, 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, param1 = 0, param2 = 0, param3 = 0, param4 = 0, chain = 'base' } = body;
  if (!walletAddress) return NextResponse.json({ error: 'Missing required field: walletAddress' }, { status: 400 });
  if (!isValidAddress(walletAddress)) return NextResponse.json({ error: 'Invalid walletAddress' }, { status: 400 });
  if (!isValidChain(chain)) return NextResponse.json({ error: 'Invalid chain' }, { status: 400 });

  const calldata = '0xcb0354f0'
    + encodeUint256(BigInt(param1))
    + encodeUint256(BigInt(param2))
    + encodeUint256(BigInt(param3))
    + encodeUint256(BigInt(param4));

  const contract = VKP_FACTORY[chain];
  if (!contract) return NextResponse.json({ error: `VKPFactory not deployed on ${chain}` }, { status: 400 });
  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 create your Vaultfire Knowledge Protocol vault on ${chain}. The vault is owned by ${walletAddress} and will hold knowledge attestations + route protocol fees.`,
    securityNote: 'Vaultfire NEVER accepts private keys. The vault is fully owner-controlled — only your wallet can authorize withdrawals or session keys.',
    _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/create-vkp-vault'), PAY_TO, {
  price: '$0.40', network: 'base',
  config: {
    description: 'Tx-prepare for VKPFactory.createVault() — create a personal Vaultfire Knowledge Protocol vault. Returns unsigned transaction; caller signs in wallet.',
    mimeType: 'application/json',
    outputSchema: {
      input: { type: 'http', method: 'POST', discoverable: true,
        bodySchema: {
          type: 'object', required: ['walletAddress'],
          properties: {
            walletAddress: { type: 'string', description: 'Owner wallet that creates the vault' },
            param1: { type: 'string', description: 'createVault uint256 arg 1 (default 0)' },
            param2: { type: 'string', description: 'createVault uint256 arg 2 (default 0)' },
            param3: { type: 'string', description: 'createVault uint256 arg 3 (default 0)' },
            param4: { type: 'string', description: 'createVault uint256 arg 4 (default 0)' },
            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' } });
}
