import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getDraft, updateDraft, deleteDraft } from '@/lib/db/draft-repo';
import { withAuth } from '@/core/auth';

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

const VerdictEnum = z.enum(['ship', 'fix', 'reject']);

/**
 * Auto-Save-Patch — alle Felder optional, nur explizit gesetzte werden geschrieben.
 * z.null() ist erlaubt für strategy/spam-Felder ('Output zurücksetzen').
 */
const PatchSchema = z.object({
  name: z.string().optional(),
  briefingJson: z.record(z.string(), z.unknown()).optional(),
  tiptapJson: z.record(z.string(), z.unknown()).optional(),
  strategyJson: z.record(z.string(), z.unknown()).nullable().optional(),
  spamScore: z.number().nullable().optional(),
  spamVerdict: VerdictEnum.nullable().optional(),
  spamReportJson: z.record(z.string(), z.unknown()).nullable().optional(),
  workspaceId: z.string().optional(),
});

export const GET = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string }> }) => {
  const { id } = await ctx.params;
  const draft = getDraft(id);
  if (!draft) return NextResponse.json({ error: 'Draft not found' }, { status: 404 });
  return NextResponse.json({ draft });
});

export const PATCH = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string }> }) => {
  const { id } = await ctx.params;
  const body = await req.json();
  const parsed = PatchSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({
      error: 'Invalid patch',
      issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
    }, { status: 400 });
  }
  const updated = updateDraft(id, parsed.data);
  if (!updated) return NextResponse.json({ error: 'Draft not found' }, { status: 404 });
  return NextResponse.json({ ok: true, draft: updated });
});

export const DELETE = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string }> }) => {
  const { id } = await ctx.params;
  const ok = deleteDraft(id);
  if (!ok) return NextResponse.json({ error: 'Draft not found' }, { status: 404 });
  return NextResponse.json({ ok: true });
});
