import { NextRequest, NextResponse } from 'next/server';
import {
  getRecipientDetail,
  getRecipientTimeline,
} from '@/lib/db/recipient-stats-repo';
import { withAuth } from '@/core/auth';

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

/**
 * Vollständige Recipient-Detail + chronologische Event-Timeline.
 * 404 wenn Recipient nicht existiert.
 *
 * Response: { ok, detail, events }
 *   detail.customDataJson enthält CRM-Felder die im Sales-Hand-off helfen
 *   events asc-sortiert nach Timestamp
 */
export const GET = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, { params }: { params: Promise<{ id: string }> }) => {
  const { id } = await params;
  if (!id) return NextResponse.json({ error: 'Missing recipient id' }, { status: 400 });

  try {
    const detail = getRecipientDetail(id);
    if (!detail) {
      return NextResponse.json({ error: 'Recipient not found' }, { status: 404 });
    }
    const events = getRecipientTimeline(id);
    return NextResponse.json({ ok: true, detail, events });
  } catch (e) {
    return NextResponse.json(
      { error: e instanceof Error ? e.message : 'Timeline lookup failed' },
      { status: 500 },
    );
  }
});
