/**
 * POST /api/x402/actions/dispute-task — $0.25 USDC
 * Calls VaultfireTaskEscrow.disputeTask(uint256 taskId, string reason)
 * Selector 0x4bddd209
 *
 * Either party can open a dispute; governance later calls resolveDispute.
 */
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, TASK_ESCROW,
  isValidAddress, isValidChain, 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, taskId, reason, chain = 'base' } = body;
  if (!walletAddress || taskId === undefined || !reason) {
    return NextResponse.json({ error: 'Missing: walletAddress, taskId, reason' }, { status: 400 });
  }
  if (!isValidAddress(walletAddress)) return NextResponse.json({ error: 'Invalid walletAddress' }, { status: 400 });
  if (!isValidChain(chain)) return NextResponse.json({ error: 'Invalid chain' }, { status: 400 });
  if (typeof reason !== 'string' || reason.length === 0 || reason.length > 4096) {
    return NextResponse.json({ error: 'reason must be a 1-4096 char string' }, { status: 400 });
  }

  let tId: bigint;
  try { tId = BigInt(taskId); } catch { return NextResponse.json({ error: 'taskId must be uint256' }, { status: 400 }); }

  // ABI-encode disputeTask(uint256, string): head=[taskId, 0x40], tail=string
  const calldata = '0x4bddd209'
    + encodeUint256(tId)
    + encodeUint256(0x40)
    + encodeString(reason);

  const contract = TASK_ESCROW[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 open a dispute on task #${tId} (${chain}). Governance can call resolveDispute to declare a winner.`,
    securityNote: 'Vaultfire NEVER accepts private keys. Either requester or assigned agent can dispute.',
    _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/dispute-task'), PAY_TO, {
  price: '$0.25', network: 'base',
  config: {
    description: 'Open a dispute on a Vaultfire task escrow. Pay $0.25 USDC, sign in your wallet — freezes the escrow pending governance resolution. Either party may dispute.',
    mimeType: 'application/json',
    outputSchema: {
      input: { type: 'http', method: 'POST', discoverable: true,
        bodySchema: {
          type: 'object', required: ['walletAddress', 'taskId', 'reason'],
          properties: {
            walletAddress: { type: 'string', description: 'Disputing party wallet that signs' },
            taskId: { type: 'string', description: 'On-chain task id (uint256)' },
            reason: { type: 'string', description: 'Plain-text reason for the dispute (1-4096 chars)' },
            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' } });
}
