#!/usr/bin/env node
/**
 * E2E 主站钱包 mock：供 transfer-in/out 异常场景（504 / 业务拒绝）。
 *
 * 控制端点：
 *   POST /_e2e/mode  body: { "mode": "success" | "504" | "reject" }
 *
 * 业务端点（与 config lottery.main_site 默认路径一致）：
 *   POST /wallet/debit-for-lottery
 *   POST /wallet/credit-from-lottery
 */

import http from 'node:http';

const PORT = Number(process.env.E2E_MOCK_WALLET_PORT ?? 5555);
let mode = process.env.E2E_MOCK_WALLET_MODE ?? 'success';

function readBody(req) {
  return new Promise((resolve) => {
    const chunks = [];
    req.on('data', (c) => chunks.push(c));
    req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
  });
}

function json(res, status, body) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(body));
}

const server = http.createServer(async (req, res) => {
  const url = req.url ?? '/';
  const method = req.method ?? 'GET';

  if (method === 'POST' && url === '/_e2e/mode') {
    try {
      const raw = await readBody(req);
      const parsed = JSON.parse(raw || '{}');
      if (typeof parsed.mode === 'string') {
        mode = parsed.mode;
      }
      json(res, 200, { mode });
    } catch {
      json(res, 400, { error: 'invalid_json' });
    }
    return;
  }

  if (method === 'GET' && url === '/_e2e/health') {
    json(res, 200, { ok: true, mode });
    return;
  }

  const isWallet =
    method === 'POST' &&
    (url === '/wallet/debit-for-lottery' || url === '/wallet/credit-from-lottery' || url.startsWith('/wallet/'));

  if (!isWallet) {
    json(res, 404, { error: 'not_found' });
    return;
  }

  if (mode === '504') {
    json(res, 504, { success: false, message: 'gateway_timeout' });
    return;
  }

  if (mode === 'reject') {
    json(res, 200, { success: false, message: 'credit_denied' });
    return;
  }

  json(res, 200, {
    success: true,
    external_ref: `mock-${Date.now()}`,
    message: 'ok',
  });
});

server.listen(PORT, '127.0.0.1', () => {
  console.log(`[e2e-mock-wallet] listening on http://127.0.0.1:${PORT} mode=${mode}`);
});
