import { NextRequest, NextResponse } from 'next/server';
import { restoreVersion } from '@/lib/db/version-repo';
import { getDraft } from '@/lib/db/draft-repo';
import { withAuth } from '@/core/auth';

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

/**
 * POST /api/drafts/[id]/versions/[versionId]/restore
 *
 * Erzeugt VOR dem Restore einen Pre-Restore-Snapshot (siehe version-repo.restoreVersion).
 * Returnt den frisch wiederhergestellten Draft, damit das Frontend ohne extra GET
 * direkt rehydraten kann.
 */
export const POST = withAuth<{ params: Promise<{ id: string; versionId: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string; versionId: string }> }) => {
  const { id, versionId } = await ctx.params;
  try {
    const { campaignId } = restoreVersion(versionId);
    if (campaignId !== id) {
      return NextResponse.json({ error: 'Version belongs to a different draft' }, { status: 400 });
    }
    const draft = getDraft(id);
    return NextResponse.json({ ok: true, draft });
  } catch (e) {
    return NextResponse.json({ error: e instanceof Error ? e.message : 'restore failed' }, { status: 500 });
  }
});
