import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { suggestBriefing } from '@/modules/briefing/lib/suggest-briefing';
import { withAuth } from '@/core/auth';

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

const RequestSchema = z.object({
  briefText: z.string(),
  briefHtml: z.string().optional(),
  existing: z.record(z.string(), z.unknown()).default({}),
});

export const POST = withAuth(async (req: NextRequest, _ctx) => {
  try {
    const body = await req.json();
    const parsed = RequestSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json({ error: 'Invalid input', details: parsed.error.flatten() }, { status: 400 });
    }
    if (parsed.data.briefText.trim().length < 10) {
      return NextResponse.json({ error: 'Brief zu kurz — schreibe mindestens 10 Zeichen im Editor' }, { status: 400 });
    }
    const result = await suggestBriefing(parsed.data);
    return NextResponse.json({
      ok: true,
      suggestions: result.suggestions,
      meta: {
        modelUsed: result.modelUsed,
        tokensIn: result.tokensIn,
        tokensOut: result.tokensOut,
        durationMs: result.durationMs,
      },
    });
  } catch (err) {
    console.error('[/api/suggest] error:', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Internal error' },
      { status: 500 },
    );
  }
});
