import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { suggestSectionContent, type SectionContent } from '@/modules/briefing/lib/suggest-section';
import { getWorkspaceBySlug } from '@/lib/db/repositories';
import { getSectionTemplate } from '@/lib/db/section-template-repo';
import { withAuth } from '@/core/auth';

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

const RequestSchema = z.object({
  workspaceSlug: z.string().min(1),
  templateId: z.string().min(1),
  briefingContext: z.object({
    campaignName: z.string().optional(),
    offer: z.string().optional(),
    painPoint: z.string().optional(),
    language: z.enum(['auto', 'de', 'en']).optional(),
    socialProof: z.string().optional(),
  }),
  mode: z.enum(['fresh', 'refine']).default('fresh'),
  currentContentText: z.string().optional(),
});

/**
 * Konvertiert SectionContent (headline + lines) zu einem TipTap-Doc.
 * Server-Side, damit der Client direkt einen TipTap-fähigen JSON-Doc bekommt.
 */
function contentToTipTap(content: SectionContent) {
  const nodes: Array<Record<string, unknown>> = [];
  if (content.headline?.trim()) {
    nodes.push({
      type: 'heading',
      attrs: { level: 3 },
      content: [{ type: 'text', text: content.headline.trim() }],
    });
  }
  for (const line of content.lines) {
    if (!line.trim()) continue;
    nodes.push({
      type: 'paragraph',
      content: [{ type: 'text', text: line.trim() }],
    });
  }
  return { type: 'doc', content: nodes };
}

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',
          issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
        },
        { status: 400 },
      );
    }

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

    const template = getSectionTemplate(parsed.data.templateId);
    if (!template) {
      return NextResponse.json({ error: `Unknown template: ${parsed.data.templateId}` }, { status: 400 });
    }

    if (template.workspaceId !== workspace.id) {
      return NextResponse.json(
        { error: 'Template does not belong to this workspace' },
        { status: 403 },
      );
    }

    const result = await suggestSectionContent({
      kind: template.kind,
      templateName: template.name,
      templateHint: template.aiPromptHint ?? undefined,
      briefingContext: parsed.data.briefingContext,
      workspace: {
        name: workspace.name,
        senderName: workspace.senderName,
        voice: workspace.brandVoice,
        wordingStyle: workspace.wordingStyle ?? undefined,
      },
      mode: parsed.data.mode,
      currentContentText: parsed.data.currentContentText,
    });

    return NextResponse.json({
      ok: true,
      tiptapJson: contentToTipTap(result.content),
      sectionContent: result.content,
      meta: {
        modelUsed: result.modelUsed,
        tokensIn: result.tokensIn,
        tokensOut: result.tokensOut,
        durationMs: result.durationMs,
      },
    });
  } catch (err) {
    console.error('[/api/suggest-section] error:', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Internal error' },
      { status: 500 },
    );
  }
});
