import { NextRequest, NextResponse } from 'next/server';
import { recordBehavior, type BehaviorType } from '@/lib/db/behavior-repo';
import { extractClientIp, hashIp } from '@/modules/stats/lib/mpp-detect';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

/**
 * Empfangs-Endpoint für Onsite-Behavior-Events von mf-track.js.
 *
 * Caller-Pattern (von mf-track.js):
 *   navigator.sendBeacon('/api/track/behavior', JSON.stringify({
 *     recipientId, campaignId, variantId, type, url, productId, value, ts, ...
 *   }));
 *
 * CORS: Wir antworten Access-Control-Allow-Origin: * weil die Origin der Workspace-Shop
 * ist (Cross-Domain). Da das Endpoint OHNE Cookies/Credentials läuft (nur Body-JSON),
 * ist `*` sicher — Caller kann nicht User-Session abgreifen.
 *
 * Best-Effort: bei jedem Fehler 200 OK + ok:false-Json statt 4xx (verhindert, dass
 * sendBeacon im Browser retry-Loops macht oder JS-Errors in der Konsole schreibt).
 */

const VALID_TYPES: BehaviorType[] = [
  'pageview',
  'product_view',
  'add_to_cart',
  'quote_form',
  'scroll_depth',
  'time_on_page',
  'custom',
];

interface BehaviorPayload {
  recipientId?: string;
  campaignId?: string;
  variantId?: string;
  type?: string;
  url?: string;
  productId?: string;
  value?: number;
  durationMs?: number;
  scrollPct?: number;
  meta?: Record<string, unknown>;
}

function corsHeaders(): Record<string, string> {
  return {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Max-Age': '86400',
  };
}

export async function OPTIONS() {
  return new NextResponse(null, { status: 204, headers: corsHeaders() });
}

export async function POST(req: NextRequest) {
  try {
    const payload = (await req.json().catch(() => null)) as BehaviorPayload | null;
    if (!payload || !payload.recipientId || !payload.type) {
      return NextResponse.json({ ok: false, reason: 'invalid_payload' }, { status: 200, headers: corsHeaders() });
    }

    if (!(VALID_TYPES as string[]).includes(payload.type)) {
      return NextResponse.json({ ok: false, reason: 'invalid_type' }, { status: 200, headers: corsHeaders() });
    }

    const ip = extractClientIp(req.headers);
    const ipHash = hashIp(ip);
    const userAgent = req.headers.get('user-agent') ?? undefined;

    const result = recordBehavior({
      recipientId: payload.recipientId,
      campaignId: payload.campaignId,
      variantId: payload.variantId,
      type: payload.type as BehaviorType,
      url: payload.url,
      productId: payload.productId,
      value: typeof payload.value === 'number' ? payload.value : undefined,
      durationMs: typeof payload.durationMs === 'number' ? payload.durationMs : undefined,
      scrollPct: typeof payload.scrollPct === 'number' ? payload.scrollPct : undefined,
      meta: payload.meta,
      userAgent,
      ipHash,
      source: 'js',
    });

    return NextResponse.json({ ok: result.ok }, { status: 200, headers: corsHeaders() });
  } catch (e) {
    console.error('[/api/track/behavior] failed:', e instanceof Error ? e.message : e);
    return NextResponse.json({ ok: false, reason: 'server_error' }, { status: 200, headers: corsHeaders() });
  }
}
