import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { draftBrief, type DraftBriefInput } from '@/modules/briefing/lib/draft-brief';
import { getWorkspaceBySlug } from '@/lib/db/repositories';
import { withAuth } from '@/core/auth';

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

// Request-Schema bewusst restriktiv auf den Pflichtfeldern — der Brief braucht alles, was sonst auch
// /api/generate braucht (campaignName, offer, painPoint, ctaPrimaryText, workspaceSlug).
// Optionale Felder werden im Prompt gerendert wenn vorhanden, sonst weggelassen.
const RequestSchema = z.object({
  campaignName: z.string().min(1),
  offer: z.string().min(1),
  painPoint: z.string().min(1),
  ctaPrimaryText: z.string().min(1),
  workspaceSlug: z.string().min(1),
  heroBriefHint: z.string().optional(),
  language: z.enum(['auto', 'de', 'en']).default('auto'),
  // Optionaler Scrape-Kontext aus dem letzten Webseiten-Scrape — gibt dem LLM mehr Wording-Inspiration.
  scrapeContext: z
    .object({
      title: z.string().optional(),
      description: z.string().optional(),
      headlines: z.array(z.string()).optional(),
      bodyText: z.string().optional(),
    })
    .optional(),
});

export const POST = withAuth(async (req: NextRequest, _ctx) => {
  try {
    const body = await req.json();
    const parsed = RequestSchema.safeParse(body);
    if (!parsed.success) {
      const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);
      console.warn('[/api/draft-brief] validation failed:', issues);
      return NextResponse.json(
        { error: 'Eingabe ungültig — bitte Briefing-Pflichtfelder prüfen', issues },
        { status: 400 },
      );
    }

    const workspace = getWorkspaceBySlug(parsed.data.workspaceSlug);
    if (!workspace) {
      return NextResponse.json({ error: `Unknown workspace: ${parsed.data.workspaceSlug}` }, { status: 400 });
    }

    const input: DraftBriefInput = {
      ...parsed.data,
      brandName: workspace.name,
      brandSenderName: workspace.senderName,
      brandVoice: workspace.brandVoice,
      brandWordingStyle: workspace.wordingStyle ?? undefined,
    };

    const result = await draftBrief(input);

    return NextResponse.json({
      ok: true,
      tiptapJson: result.tiptap.json,
      html: result.tiptap.html,
      text: result.tiptap.text,
      sections: result.sections,
      meta: {
        modelUsed: result.modelUsed,
        tokensIn: result.tokensIn,
        tokensOut: result.tokensOut,
        durationMs: result.durationMs,
      },
    });
  } catch (err) {
    console.error('[/api/draft-brief] error:', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Internal error' },
      { status: 500 },
    );
  }
});
