import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { createDraftFromTemplate, deleteTemplate } from '@/lib/db/template-repo';
import { withAuth } from '@/core/auth';

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

const InstantiateSchema = z.object({
  name: z.string().optional(),
});

/**
 * POST /api/templates/[id]
 *
 * Erzeugt einen neuen Draft aus dieser Vorlage (Briefing + Tiptap-Inhalt werden kopiert).
 * Die Vorlage selbst bleibt unverändert.
 */
export const POST = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string }> }) => {
  const { id } = await ctx.params;
  const body = await req.json().catch(() => ({}));
  const parsed = InstantiateSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: 'Invalid input' }, { status: 400 });
  }
  try {
    const draft = createDraftFromTemplate(id, parsed.data.name);
    return NextResponse.json({ ok: true, draft });
  } catch (e) {
    return NextResponse.json({ error: e instanceof Error ? e.message : 'instantiate failed' }, { status: 500 });
  }
});

export const DELETE = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, ctx: { params: Promise<{ id: string }> }) => {
  const { id } = await ctx.params;
  const ok = deleteTemplate(id);
  if (!ok) return NextResponse.json({ error: 'Template not found' }, { status: 404 });
  return NextResponse.json({ ok: true });
});
