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

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

const SaveSchema = z.object({
  draftId: z.string().min(1),
  name: z.string().min(1),
  description: z.string().optional(),
});

export const GET = withAuth(async (req: NextRequest, _ctx) => {
  return NextResponse.json({ templates: listTemplates() });
});

export const POST = withAuth(async (req: NextRequest, _ctx) => {
  const body = await req.json();
  const parsed = SaveSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({
      error: 'Invalid template input',
      issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
    }, { status: 400 });
  }
  try {
    const template = saveAsTemplate(parsed.data);
    return NextResponse.json({ ok: true, template });
  } catch (e) {
    return NextResponse.json({ error: e instanceof Error ? e.message : 'save template failed' }, { status: 500 });
  }
});
