/**
 * POST /api/x402/actions/report-mission-violation — $0.15 USDC
 * Calls MissionEnforcement.reportMissionViolation(address module, uint8 principle, string evidence)
 * Selector 0x8100f15e
 */
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, MISSION_ENFORCEMENT, SUPPORTED_CHAINS,
  isValidAddress, isValidChain, encodeAddress, encodeUint256, 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, module, principle, evidence, chain = 'base' } = body;
  if (!walletAddress || !module || principle === undefined || !evidence) {
    return NextResponse.json({ error: 'Missing: walletAddress, module, principle, evidence' }, { status: 400 });
  }
  if (!isValidAddress(walletAddress) || !isValidAddress(module)) return NextResponse.json({ error: 'Invalid address' }, { status: 400 });
  if (!isValidChain(chain)) return NextResponse.json({ error: 'Invalid chain' }, { status: 400 });
  const p = Number(principle);
  if (!Number.isInteger(p) || p < 0 || p > 255) return NextResponse.json({ error: 'principle must be uint8 (0-255)' }, { status: 400 });

  // reportMissionViolation(address, uint8, string)
  // head: address(32) + uint8(32) + offset_string(32) = 0x60
  const calldata = '0x8100f15e'
    + encodeAddress(module)
    + encodeUint256(BigInt(p))
    + encodeUint256(0x60)
    + encodeString(String(evidence));

  const contract = MISSION_ENFORCEMENT[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 report mission violation against ${module} on ${chain} (principle: ${p}).`,
    securityNote: 'Vaultfire NEVER accepts private keys.',
    _x402: { paid: true, price: '$0.15 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.15', '/actions/report-mission-violation'), PAY_TO, {
  price: '$0.15', network: 'base',
  config: {
    description: 'Report a mission violation against a module on Vaultfire MissionEnforcement. Pay $0.15 USDC, sign in your wallet — files a violation under one of the protocol mission principles with on-chain evidence.',
    mimeType: 'application/json',
    outputSchema: {
      input: { type: 'http', method: 'POST', discoverable: true,
        bodySchema: {
          type: 'object', required: ['walletAddress', 'module', 'principle', 'evidence'],
          properties: {
            walletAddress: { type: 'string' }, module: { type: 'string', description: 'Address of module being reported' },
            principle: { type: 'string', description: 'uint8 principle index' }, evidence: { 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' } });
}
