/**
 * POST /api/x402/actions/file-insurance-claim — $0.30 USDC
 * Calls VaultfireBondInsurancePool.submitClaim(uint256,string,bytes32)
 * Selector 0x8f7e9eb1 (verified byte-equal vs canonical hardhat artifact)
 */
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, BOND_INSURANCE_POOL,
  isValidAddress, isValidBytes32, isValidChain, encodeUint256, encodeString, encodeBytes32, 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, bondId, reason, evidenceHash, chain = 'base' } = body;
  if (!walletAddress || bondId === undefined || !reason || !evidenceHash) {
    return NextResponse.json({ error: 'Missing required fields: walletAddress, bondId, reason, evidenceHash' }, { status: 400 });
  }
  if (!isValidAddress(walletAddress)) return NextResponse.json({ error: 'Invalid walletAddress' }, { status: 400 });
  if (!isValidBytes32(evidenceHash)) return NextResponse.json({ error: 'evidenceHash must be 0x + 64 hex chars (bytes32)' }, { status: 400 });
  if (!isValidChain(chain)) return NextResponse.json({ error: 'Invalid chain' }, { status: 400 });
  if (typeof reason !== 'string' || reason.length === 0 || reason.length > 1024) {
    return NextResponse.json({ error: 'reason must be a string of 1-1024 chars' }, { status: 400 });
  }

  // submitClaim(uint256,string,bytes32) — head: bondId | offset_to_string(0x60) | evidenceHash
  const head = encodeUint256(BigInt(bondId)) + encodeUint256(0x60) + encodeBytes32(evidenceHash);
  const calldata = '0x8f7e9eb1' + head + encodeString(reason);

  const contract = BOND_INSURANCE_POOL[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 file an insurance claim against bond #${bondId} on ${chain}. Pool governance reviews and resolves.`,
    securityNote: 'Vaultfire NEVER accepts private keys. False claims forfeit insurance contributions.',
    _x402: { paid: true, price: '$0.30 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.30', '/actions/file-insurance-claim'), PAY_TO, {
  price: '$0.30', network: 'base',
  config: {
    description: 'Tx-prepare for VaultfireBondInsurancePool.submitClaim() — file an insurance claim against a defaulted bond. Returns unsigned transaction; caller signs in wallet.',
    mimeType: 'application/json',
    outputSchema: {
      input: { type: 'http', method: 'POST', discoverable: true,
        bodySchema: {
          type: 'object', required: ['walletAddress', 'bondId', 'reason', 'evidenceHash'],
          properties: {
            walletAddress: { type: 'string' },
            bondId: { type: 'string', description: 'On-chain bond id being claimed against' },
            reason: { type: 'string', description: 'Human-readable reason for the claim (1-1024 chars)' },
            evidenceHash: { type: 'string', description: 'bytes32 hash of supporting evidence (e.g. IPFS CID hash)' },
            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' } });
}
