import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  getBouncePollingSettings,
  setBouncePollingSettings,
} from '@/modules/sending/lib/inbox-scanner';
import { withAuth } from '@/core/auth';

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

/**
 * Settings-Endpoint für Phase-3 Bounce-Inbox-Polling.
 *
 * Spiegelt das Pattern von /api/settings/conversion-polling — eigener Endpoint
 * weil orthogonal zum Rest und der Worker direkt aus app_settings.bounce_polling
 * liest.
 */

const PatchSchema = z.object({
  enabled: z.boolean().optional(),
  intervalMinutes: z.number().int().min(1).max(1440).optional(),
  senderMailboxes: z.array(z.string().email()).optional(),
  /** Setzt lastScanAt explizit zurück — Worker fängt dann beim nächsten Tick neu an. */
  resetLastScanAt: z.boolean().optional(),
});

export const GET = withAuth(async (req: NextRequest, _ctx) => {
  try {
    return NextResponse.json(getBouncePollingSettings());
  } 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 = getBouncePollingSettings();
    const next = { ...cur };
    if (parsed.data.enabled !== undefined) next.enabled = parsed.data.enabled;
    if (parsed.data.intervalMinutes !== undefined) next.intervalMinutes = parsed.data.intervalMinutes;
    if (parsed.data.senderMailboxes !== undefined) next.senderMailboxes = parsed.data.senderMailboxes;
    if (parsed.data.resetLastScanAt) next.lastScanAt = undefined;
    setBouncePollingSettings(next);

    return NextResponse.json(next);
  } catch (e) {
    return NextResponse.json({ error: e instanceof Error ? e.message : 'Update failed' }, { status: 500 });
  }
});
