import { NextRequest, NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { db } from '@/lib/db/client';
import { workspaces } from '@/lib/db/schema';
import { verifySignature, readSignatureHeader } from '@/modules/stats/lib/webhook-signature';
import { recordBehavior, type BehaviorType } from '@/lib/db/behavior-repo';
import { recordConversion } from '@/lib/db/campaign-repo';

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

/**
 * Server-zu-Server Webhook-Empfänger für Shop-/CRM-Push-Events.
 *
 * Authentifizierung: HMAC-SHA256 über Body, Workspace-Secret in workspaces.webhookSecret.
 * Header: X-MailForge-Signature: sha256=<hex>
 *
 * Body-Schema:
 * {
 *   "recipientId": "uuid",          // Pflicht — der Empfänger der zugeordnet werden soll
 *   "event": "add_to_cart" | "product_view" | "quote_form" | "conversion" | "...",
 *   "value": 2990,                  // optional, in EUR-Cent oder Punkten
 *   "productId": "ABC-123",         // optional
 *   "url": "https://...",            // optional
 *   "meta": { ... }                 // optional, beliebige Zusatzdaten
 * }
 *
 * Conversion-Events (event='conversion') landen in tracking_events.conversion
 * mit source='webhook'. Alle anderen Events landen in behavior_events.
 *
 * Antwort-Codes:
 *  - 200 OK: erfolgreich verarbeitet
 *  - 401 Unauthorized: Signatur fehlt oder ist falsch
 *  - 404 Not Found: Workspace-Slug existiert nicht
 *  - 400 Bad Request: Body unbrauchbar
 */

const BEHAVIOR_EVENT_TYPES = new Set<BehaviorType>([
  'pageview',
  'product_view',
  'add_to_cart',
  'quote_form',
  'scroll_depth',
  'time_on_page',
  'custom',
]);

interface WebhookPayload {
  recipientId?: string;
  event?: string;
  value?: number;
  productId?: string;
  url?: string;
  meta?: Record<string, unknown>;
}

export async function POST(req: NextRequest, { params }: { params: Promise<{ workspaceSlug: string }> }) {
  const { workspaceSlug } = await params;
  if (!workspaceSlug) {
    return NextResponse.json({ error: 'Missing workspace slug' }, { status: 400 });
  }

  const workspace = db
    .select({ id: workspaces.id, webhookSecret: workspaces.webhookSecret })
    .from(workspaces)
    .where(eq(workspaces.slug, workspaceSlug))
    .get();

  if (!workspace) {
    return NextResponse.json({ error: 'Workspace not found' }, { status: 404 });
  }

  if (!workspace.webhookSecret) {
    // Kein Secret konfiguriert — Endpoint ist defensiv deaktiviert
    return NextResponse.json({ error: 'Webhook nicht konfiguriert' }, { status: 401 });
  }

  // Body als Raw-String lesen, weil die Signatur über den exakten Body läuft
  const rawBody = await req.text();
  const signature = readSignatureHeader(req.headers);
  if (!verifySignature(rawBody, signature, workspace.webhookSecret)) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
  }

  let payload: WebhookPayload;
  try {
    payload = JSON.parse(rawBody) as WebhookPayload;
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  if (!payload.recipientId || !payload.event) {
    return NextResponse.json({ error: 'recipientId and event required' }, { status: 400 });
  }

  // Conversion-Pfad
  if (payload.event === 'conversion') {
    const result = recordConversion({
      recipientId: payload.recipientId,
      value: typeof payload.value === 'number' ? payload.value : undefined,
      meta: payload.meta,
      source: 'webhook',
    });
    return NextResponse.json({ ok: result.ok, ...(result.ok ? { eventId: result.eventId } : { reason: result.reason }) });
  }

  // Behavior-Pfad
  if (!BEHAVIOR_EVENT_TYPES.has(payload.event as BehaviorType)) {
    return NextResponse.json({ error: `Unknown event type '${payload.event}'` }, { status: 400 });
  }

  const result = recordBehavior({
    recipientId: payload.recipientId,
    type: payload.event as BehaviorType,
    url: payload.url,
    productId: payload.productId,
    value: typeof payload.value === 'number' ? payload.value : undefined,
    meta: payload.meta,
    source: 'webhook',
  });

  return NextResponse.json({ ok: result.ok, ...(result.ok ? { eventId: result.eventId } : { reason: result.reason }) });
}
