import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getSectionTemplate, updateSectionTemplate, deleteSectionTemplate } from '@/lib/db/section-template-repo';
import { withAuth } from '@/core/auth';

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

const PatchSchema = z.object({
  name: z.string().min(1).max(120).optional(),
  description: z.string().optional(),
  defaultContentJson: z.record(z.string(), z.unknown()).optional(),
  mjmlBlock: z.string().min(20).optional(),
  aiPromptHint: z.string().optional(),
  defaultPosition: z
    .enum(['before_cta', 'after_cta', 'before_signature', 'after_signature'])
    .optional(),
  bodyMode: z.enum(['tiptap', 'mjml_raw', 'html_raw']).optional(),
});

interface Ctx {
  params: Promise<{ id: string }>;
}

export const GET = withAuth<Ctx>(async (req: NextRequest, _ctx, { params }: Ctx) => {
  const { id } = await params;
  const t = getSectionTemplate(id);
  if (!t) return NextResponse.json({ error: 'Not found' }, { status: 404 });
  return NextResponse.json({ ok: true, section: t });
});

export const PATCH = withAuth<Ctx>(async (req: NextRequest, _ctx, { params }: Ctx) => {
  const { id } = await params;
  try {
    const body = await req.json();
    const parsed = PatchSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        {
          error: 'Invalid patch',
          issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
        },
        { status: 400 },
      );
    }
    const updated = updateSectionTemplate(id, parsed.data);
    if (!updated) return NextResponse.json({ error: 'Not found' }, { status: 404 });
    return NextResponse.json({ ok: true, section: updated });
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Internal error' },
      { status: 500 },
    );
  }
});

export const DELETE = withAuth<Ctx>(async (req: NextRequest, _ctx, { params }: Ctx) => {
  const { id } = await params;
  const ok = deleteSectionTemplate(id);
  if (!ok) {
    return NextResponse.json(
      { error: 'Not found or system template (cannot be deleted)' },
      { status: 400 },
    );
  }
  return NextResponse.json({ ok: true });
});
