import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  createDraft,
  listDrafts,
  listRecentDrafts,
  listDraftsGroupedByBrand,
} from '@/lib/db/draft-repo';
import { withAuth } from '@/core/auth';

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

const CreateDraftSchema = z.object({
  workspaceId: z.string().min(1),
  name: z.string().optional(),
  briefingJson: z.record(z.string(), z.unknown()).optional(),
  tiptapJson: z.record(z.string(), z.unknown()).optional(),
});

/**
 * GET /api/drafts
 *  - default:           flache Liste aller Drafts (sortiert updatedAt desc)
 *  - ?view=grouped      gruppiert nach Workspace (für die Projekte-Sektion der Sidebar)
 *  - ?view=recent&n=5   Top-N nach updatedAt
 */
export const GET = withAuth(async (req: NextRequest, _ctx) => {
  const view = req.nextUrl.searchParams.get('view');
  if (view === 'grouped') {
    return NextResponse.json({ groups: listDraftsGroupedByBrand() });
  }
  if (view === 'recent') {
    const n = parseInt(req.nextUrl.searchParams.get('n') ?? '5', 10);
    return NextResponse.json({ drafts: listRecentDrafts(Number.isNaN(n) ? 5 : n) });
  }
  return NextResponse.json({ drafts: listDrafts() });
});

export const POST = withAuth(async (req: NextRequest, _ctx) => {
  const body = await req.json();
  const parsed = CreateDraftSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({
      error: 'Invalid draft',
      issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
    }, { status: 400 });
  }
  try {
    const draft = createDraft(parsed.data);
    return NextResponse.json({ ok: true, draft });
  } catch (e) {
    return NextResponse.json({ error: e instanceof Error ? e.message : 'create failed' }, { status: 500 });
  }
});
