/**
 * config/alertTestMode.js
 *
 * If NCII_ALERT_TEST_MODE=1, external services (resend, scrapedo, MiniMax) are
 * SHIMMED with a fake adapter that returns a synthetic error matching the
 * real one's shape. This lets us exercise the alert pipeline end-to-end
 * without burning any real quota.
 *
 * Trigger from the admin panel: POST /admin/alerts/test-failure
 * Or from env: NCII_ALERT_TEST_MODE=1 node app.js
 */

'use strict';

const isTestMode = () => process.env.NCII_ALERT_TEST_MODE === '1';

function maybeApplyShim() {
  if (!isTestMode()) return;
  // Shim email.js sendRaw so it throws an error that looks like a 401.
  // We do NOT touch the real adapters — we replace them at runtime.
  const email = require('./email');
  const realSendRaw = email.sendRaw;
  email.sendRaw = async function shimmedSendRaw(to, subject, body, opts = {}) {
    // 50% chance 401 (quota), 50% chance 503 (transient)
    const code = Math.random() < 0.5 ? 401 : 503;
    const msg = code === 401
      ? 'resend 401: {"statusCode":401,"name":"validation_error","message":"API key is invalid"}'
      : 'resend 503: upstream temporarily unavailable';
    throw new Error(msg);
  };
  console.warn('[alertTestMode] email.sendRaw SHIMMED — real Resend calls will not be made');
}

module.exports = { isTestMode, maybeApplyShim };
