import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  listSectionTemplatesByBrandSlug,
  createSectionTemplate,
} from '@/lib/db/section-template-repo';
import { getWorkspaceBySlug } from '@/lib/db/repositories';
import { withAuth } from '@/core/auth';

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

const KIND_VALUES = ['contact_service', 'app_download', 'testimonial', 'faq', 'custom'] as const;
type SectionKindParam = (typeof KIND_VALUES)[number];

/** GET /api/section-templates?workspaceSlug=…&kind=custom — listet Workspace-Section-Templates, optional gefiltert nach kind. */
export const GET = withAuth(async (req: NextRequest, _ctx) => {
  const slug = req.nextUrl.searchParams.get('workspaceSlug');
  if (!slug) {
    return NextResponse.json({ error: 'workspaceSlug query param required' }, { status: 400 });
  }
  const kindParam = req.nextUrl.searchParams.get('kind');
  const kindFilter = kindParam && (KIND_VALUES as readonly string[]).includes(kindParam)
    ? (kindParam as SectionKindParam)
    : undefined;
  const sections = listSectionTemplatesByBrandSlug(slug, kindFilter);
  return NextResponse.json({ ok: true, sections });
});

const CreateSchema = z.object({
  workspaceSlug: z.string().min(1),
  kind: z.enum(['contact_service', 'app_download', 'testimonial', 'faq', 'custom']).default('custom'),
  name: z.string().min(1).max(120),
  description: z.string().optional(),
  defaultContentJson: z.record(z.string(), z.unknown()),
  mjmlBlock: z.string().min(20),
  aiPromptHint: z.string().optional(),
  defaultPosition: z
    .enum(['before_cta', 'after_cta', 'before_signature', 'after_signature'])
    .default('before_signature'),
  /**
   * Body-Modus des Templates. Bei 'mjml_raw'/'html_raw' enthält mjmlBlock einen vom
   * User importierten Block (kein {{TIPTAP_HTML}}-Slot). KI-Vorschlag wird im UI deaktiviert.
   */
  bodyMode: z.enum(['tiptap', 'mjml_raw', 'html_raw']).default('tiptap'),
});

/** POST /api/section-templates — legt eine neue (Custom-)Section an. */
export const POST = withAuth(async (req: NextRequest, _ctx) => {
  try {
    const body = await req.json();
    const parsed = CreateSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        {
          error: 'Invalid payload',
          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 created = createSectionTemplate({
      workspaceId: workspace.id,
      kind: parsed.data.kind,
      name: parsed.data.name,
      description: parsed.data.description,
      defaultContentJson: parsed.data.defaultContentJson,
      mjmlBlock: parsed.data.mjmlBlock,
      aiPromptHint: parsed.data.aiPromptHint,
      defaultPosition: parsed.data.defaultPosition,
      bodyMode: parsed.data.bodyMode,
      isSystem: false,
    });

    return NextResponse.json({ ok: true, section: created });
  } catch (err) {
    console.error('[/api/section-templates POST] error:', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Internal error' },
      { status: 500 },
    );
  }
});
