import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  getConversionPollingSettings,
  setConversionPollingSettings,
  type ConversionPollingSource,
} from '@/modules/stats/lib/cumas-poller';
import { withAuth } from '@/core/auth';

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

/**
 * Settings-Endpoint für Phase-3b Conversion-Polling.
 *
 * Eigener Endpoint statt im großen Settings-Bundle, weil:
 *  - Polling-Config ist orthogonal zu Workspace-/Prompt-Settings
 *  - Erleichtert späteres Hinzufügen weiterer Polling-Quellen
 *  - Worker liest direkt aus app_settings.conversion_polling — keine Cache-Invalidation nötig
 *
 * Reset-Mechanismus für lastPolledAt (z.B. nach Pause): einfach `lastPolledAt: {}` PATCHen,
 * dann fängt der nächste Poll-Tick beim aktuellen Zeitpunkt an.
 */

const PollingSourceSchema = z.enum(['cumas_orderPrivateShop', 'cumas_evb']);

/**
 * Cumas-Feldname für Recipient-ID-Match, pro Quelle. Dot-Path wie 'extra_data.mf_rcp'.
 * Erlaubt: a-z, A-Z, 0-9, '.', '_', '-'. Leerstring im JSON → Feld wird entfernt (Email-Fallback).
 */
const RecipientIdFieldSchema = z.string().regex(/^[A-Za-z0-9_.\-]*$/).max(120);

const PatchSchema = z.object({
  enabled: z.boolean().optional(),
  intervalMinutes: z.number().int().min(1).max(1440).optional(),
  sources: z.array(PollingSourceSchema).min(1).optional(),
  // lastPolledAt: nicht via Patch updatebar (Worker-internal) — außer explizit zum Reset
  resetLastPolledAt: z.boolean().optional(),
  recipientIdField: z.object({
    cumas_orderPrivateShop: RecipientIdFieldSchema.optional(),
    cumas_evb: RecipientIdFieldSchema.optional(),
  }).optional(),
});

export const GET = withAuth(async (req: NextRequest, _ctx) => {
  try {
    return NextResponse.json(getConversionPollingSettings());
  } catch (e) {
    return NextResponse.json({ error: e instanceof Error ? e.message : 'Lookup failed' }, { status: 500 });
  }
});

export const PATCH = withAuth(async (req: NextRequest, _ctx) => {
  try {
    const body = await req.json();
    const parsed = PatchSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        { error: 'Invalid payload', issues: parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`) },
        { status: 400 },
      );
    }

    const cur = getConversionPollingSettings();
    // Bei recipientIdField-Patch: leere Strings als 'feld entfernen' interpretieren.
    let nextRcpField = cur.recipientIdField;
    if (parsed.data.recipientIdField) {
      const merged: Partial<Record<ConversionPollingSource, string>> = { ...(cur.recipientIdField ?? {}) };
      for (const src of ['cumas_orderPrivateShop', 'cumas_evb'] as const) {
        const v = parsed.data.recipientIdField[src];
        if (v === undefined) continue;
        if (v === '') delete merged[src];
        else merged[src] = v;
      }
      nextRcpField = merged;
    }
    const next = {
      ...cur,
      enabled: parsed.data.enabled ?? cur.enabled,
      intervalMinutes: parsed.data.intervalMinutes ?? cur.intervalMinutes,
      sources: parsed.data.sources ?? cur.sources,
      lastPolledAt: parsed.data.resetLastPolledAt ? {} as Partial<Record<ConversionPollingSource, string>> : cur.lastPolledAt,
      recipientIdField: nextRcpField,
    };
    setConversionPollingSettings(next);
    return NextResponse.json(next);
  } catch (e) {
    return NextResponse.json({ error: e instanceof Error ? e.message : 'Update failed' }, { status: 500 });
  }
});
