/**
 * Tests für Phase-1 Attribution-Bausteine:
 *  - appendAttributionParams (in track/click/route.ts duplicate-implementiert hier
 *    weil die Route ein NextRequest-Handler ist; die Logik ist die gleiche)
 *  - buildLoginLink mit recipientId
 *  - getByPath aus cumas-poller
 *
 * Aufruf: `npx tsx scripts/test-attribution.ts`
 */
import { buildLoginLink } from '../src/adapters/crm/cumas-login-link';

let failed = 0;
let passed = 0;

function check(name: string, cond: boolean, detail?: string) {
  if (cond) {
    passed++;
    console.log(`  ✓ ${name}`);
  } else {
    failed++;
    console.log(`  ✗ ${name}${detail ? ` — ${detail}` : ''}`);
  }
}
function section(t: string) { console.log(`\n${t}`); }

// ─── appendAttributionParams (lokale Kopie der Logik aus route.ts) ──────────
function appendAttributionParams(
  to: string,
  recipientId: string | undefined,
  campaignId: string | null,
  variantId: string | null,
): string {
  try {
    const url = new URL(to);
    if (recipientId && !url.searchParams.has('mf_rcp')) url.searchParams.set('mf_rcp', recipientId);
    if (campaignId && !url.searchParams.has('mf_cmp')) url.searchParams.set('mf_cmp', campaignId);
    if (variantId && !url.searchParams.has('mf_v')) url.searchParams.set('mf_v', variantId);
    return url.toString();
  } catch {
    return to;
  }
}

section('Click-Redirect Attribution-Params');
{
  const out = appendAttributionParams('https://www.versicherungsspartarif.de/start', 'rec-123', 'cmp-456', 'var-789');
  const url = new URL(out);
  check('mf_rcp gesetzt', url.searchParams.get('mf_rcp') === 'rec-123');
  check('mf_cmp gesetzt', url.searchParams.get('mf_cmp') === 'cmp-456');
  check('mf_v gesetzt', url.searchParams.get('mf_v') === 'var-789');
}
{
  // Existierende Params bleiben unverändert
  const out = appendAttributionParams('https://shop.de/x?utm_source=email&mf_rcp=manual', 'rec-123', 'cmp-456', null);
  const url = new URL(out);
  check('existierendes mf_rcp wird NICHT überschrieben', url.searchParams.get('mf_rcp') === 'manual');
  check('utm_source bleibt', url.searchParams.get('utm_source') === 'email');
  check('mf_cmp wird angehängt', url.searchParams.get('mf_cmp') === 'cmp-456');
  check('mf_v fehlt (war null)', url.searchParams.get('mf_v') === null);
}
{
  // Recipient undefined → kein mf_rcp
  const out = appendAttributionParams('https://shop.de/x', undefined, 'cmp-1', 'var-1');
  const url = new URL(out);
  check('ohne recipientId kein mf_rcp', url.searchParams.get('mf_rcp') === null);
  check('aber mf_cmp da', url.searchParams.get('mf_cmp') === 'cmp-1');
}

section('buildLoginLink mit recipientId');
{
  const link = buildLoginLink('https://www.versicherungsspartarif.de', '123168', 'private', 'rec-abc');
  check('enthält /willkommen', link.includes('/willkommen?'));
  check('enthält kid', /kid=[^&]+/.test(link));
  check('enthält mf_rcp', link.includes('&mf_rcp=rec-abc'));
  check('kein type=business (private)', !link.includes('type=business'));
}
{
  const link = buildLoginLink('https://www.versicherungsspartarif.de', '180480', 'business', 'rec-xyz');
  check('enthält type=business', link.includes('&type=business'));
  check('enthält mf_rcp nach type', link.indexOf('mf_rcp=') > link.indexOf('type=business'));
}
{
  // Ohne recipientId → kein mf_rcp
  const link = buildLoginLink('https://shop.de', '123', 'private');
  check('ohne recipientId kein mf_rcp', !link.includes('mf_rcp='));
}

section('Cumas getByPath (duplicate der Logik)');
function getByPath(obj: unknown, path: string): string | undefined {
  if (!path || obj === null || obj === undefined) return undefined;
  const parts = path.split('.');
  let cur: unknown = obj;
  for (const p of parts) {
    if (cur === null || cur === undefined || typeof cur !== 'object') return undefined;
    cur = (cur as Record<string, unknown>)[p];
  }
  if (typeof cur === 'string' && cur.trim().length > 0) return cur.trim();
  if (typeof cur === 'number') return String(cur);
  return undefined;
}
{
  const obj = { extra_data: { mf_rcp: 'rec-deep' }, customer_note: 'note-1' };
  check('Dot-Path findet nested', getByPath(obj, 'extra_data.mf_rcp') === 'rec-deep');
  check('Top-Level Feld', getByPath(obj, 'customer_note') === 'note-1');
  check('Nicht existierend → undefined', getByPath(obj, 'extra_data.missing') === undefined);
  check('Tieferer Pfad bricht sauber', getByPath(obj, 'extra_data.mf_rcp.deep') === undefined);
  check('Leerer Pfad → undefined', getByPath(obj, '') === undefined);
  check('Number wird zu String', getByPath({ id: 42 }, 'id') === '42');
  check('Leerstring-Value → undefined', getByPath({ x: '   ' }, 'x') === undefined);
}

console.log(`\n${passed} passed, ${failed} failed`);
if (failed > 0) process.exit(1);
