import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

/**
 * GET  /api/ai/templates  — built-ins (userId IS NULL) + this user's own
 * POST /api/ai/templates  — create a user-owned template
 */

export async function GET() {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const templates = await prisma.aIPromptTemplate.findMany({
    where: { OR: [{ userId: null }, { userId: user.id }] },
    orderBy: [{ isBuiltIn: 'desc' }, { name: 'asc' }],
  });
  return NextResponse.json(templates);
}

const createSchema = z.object({
  name: z.string().min(1),
  description: z.string().optional().nullable(),
  systemPrompt: z.string().min(1),
  userPromptTemplate: z.string().min(1),
});

export async function POST(request: NextRequest) {
  try {
    const user = await getCurrentUser();
    if (!user)
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const body = await request.json().catch(() => ({}));
    const parsed = createSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        { error: 'Invalid body', details: parsed.error.errors },
        { status: 400 },
      );
    }

    const tpl = await prisma.aIPromptTemplate.create({
      data: {
        userId: user.id,
        name: parsed.data.name,
        description: parsed.data.description ?? null,
        systemPrompt: parsed.data.systemPrompt,
        userPromptTemplate: parsed.data.userPromptTemplate,
        isBuiltIn: false,
      },
    });
    return NextResponse.json(tpl, { status: 201 });
  } catch (err) {
    console.error('POST /api/ai/templates error:', err);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 },
    );
  }
}
