/**
 * GET  /api/agent/tasks?chain=base              — Read on-chain task stats
 * POST /api/agent/tasks                          — Prepare a createTask transaction
 *
 * VaultfireTaskEscrow — Trustless USDC task escrow across 4 chains.
 * Agents post tasks, other agents bid/complete, escrow releases on completion.
 * 1 % protocol fee. All funds held by the smart contract — never by this API.
 *
 * SECURITY: This route NEVER accepts or handles private keys.
 * All signing is done client-side via the caller's wallet.
 */

import { NextRequest, NextResponse } from 'next/server';
import { resolveChain, SUPPORTED_CHAINS } from '../../_lib/resolve-chain';
import {
  TASK_ESCROW,
  CHAIN_IDS,
  RPC_URLS,
  EXPLORER_URLS,
  type SupportedChain,
} from '../../../lib/contracts';
import { checkRateLimit, RATE_LIMIT_GET, RATE_LIMIT_WRITE } from '../../../lib/rate-limit';

/* ── CORS ── */
const CORS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type',
};
export async function OPTIONS() {
  return new NextResponse(null, { status: 204, headers: CORS });
}

/* ── Selectors ── */
const NEXT_TASK_ID = '0x1a7a98e2';   // nextTaskId()
const PROTOCOL_FEE  = '0xd1ff8f3d';  // protocolFeeBps()

async function rpcCall(rpc: string, to: string, data: string): Promise<string> {
  const res = await fetch(rpc, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_call', params: [{ to, data }, 'latest'] }),
  });
  const json = await res.json();
  return json.result || '0x0';
}

/* ── GET — read on-chain stats ── */
export async function GET(request: NextRequest) {
  const rl = checkRateLimit(request, RATE_LIMIT_GET);
  if (rl) return rl;

  const chain = resolveChain(request.nextUrl.searchParams.get('chain')) as SupportedChain;
  if (!chain || !SUPPORTED_CHAINS.includes(chain)) {
    return NextResponse.json({ error: `Invalid chain. Use: ${SUPPORTED_CHAINS.join(', ')}` }, { status: 400, headers: CORS });
  }

  const contract = TASK_ESCROW[chain];
  const rpc = RPC_URLS[chain];

  try {
    const [rawTaskId, rawFee] = await Promise.all([
      rpcCall(rpc, contract, NEXT_TASK_ID),
      rpcCall(rpc, contract, PROTOCOL_FEE),
    ]);

    return NextResponse.json({
      chain,
      contract,
      chainId: CHAIN_IDS[chain],
      totalTasks: parseInt(rawTaskId, 16) || 0,
      protocolFeeBps: parseInt(rawFee, 16) || 100,
      explorerUrl: `${EXPLORER_URLS[chain]}/address/${contract}`,
    }, { headers: CORS });
  } catch {
    return NextResponse.json({ error: 'Failed to read on-chain data' }, { status: 502, headers: CORS });
  }
}

/* ── POST — prepare unsigned createTask tx ── */
function pad32(hex: string): string { return hex.replace('0x', '').toLowerCase().padStart(64, '0'); }
function encodeUint(n: bigint): string { return n.toString(16).padStart(64, '0'); }

export async function POST(request: NextRequest) {
  const rl = checkRateLimit(request, RATE_LIMIT_WRITE);
  if (rl) return rl;

  try {
    const body = await request.json();
    if (body.privateKey || body.private_key) {
      return NextResponse.json({ error: 'SECURITY: This endpoint does not accept private keys.' }, { status: 400, headers: CORS });
    }

    const { walletAddress, usdcAmount, description, deadline, chain: rawChain = 'base' } = body;
    const chain = resolveChain(rawChain) as SupportedChain;

    if (!walletAddress || !usdcAmount) {
      return NextResponse.json({ error: 'Missing required fields: walletAddress, usdcAmount' }, { status: 400, headers: CORS });
    }
    if (!chain || !SUPPORTED_CHAINS.includes(chain)) {
      return NextResponse.json({ error: `Invalid chain. Use: ${SUPPORTED_CHAINS.join(', ')}` }, { status: 400, headers: CORS });
    }

    const contract = TASK_ESCROW[chain];
    const amount = BigInt(Math.floor(parseFloat(usdcAmount) * 1e6)); // USDC has 6 decimals

    // createTask(uint256 amount, string calldata desc, uint256 deadline) → selector TBD
    // For now return the contract + ABI info so the agent can encode locally
    return NextResponse.json({
      success: true,
      contract,
      chain,
      chainId: CHAIN_IDS[chain],
      usdcAmount: parseFloat(usdcAmount),
      usdcAmountRaw: amount.toString(),
      explorerUrl: `${EXPLORER_URLS[chain]}/address/${contract}`,
      message: `Approve USDC then call createTask on ${contract}. The escrow holds funds until task completion.`,
      abi: {
        createTask: 'createTask(uint256,string,uint256)',
        completeTask: 'completeTask(uint256)',
        cancelTask: 'cancelTask(uint256)',
        getTask: 'getTask(uint256)',
      },
    }, { headers: CORS });
  } catch {
    return NextResponse.json({ error: 'Internal server error' }, { status: 500, headers: CORS });
  }
}
