import { NextResponse } from 'next/server'
import { prisma } from '@/lib/db'

/**
 * GET /api/templates
 * Listet alle verfügbaren Vorlagen-Pakete mit Vorschau.
 */
export async function GET() {
  try {
    const packages = await (prisma as any).symbolTemplate.groupBy({
      by: ['packageId', 'packageName'],
      _count: { id: true },
    })

    const result = await Promise.all(
      packages.map(async (pkg: any) => {
        // Get category breakdown for this package
        const categories = await (prisma as any).symbolTemplate.groupBy({
          by: ['categoryName'],
          where: { packageId: pkg.packageId },
          _count: { id: true },
        })

        // Get a few preview symbols
        const previews = await (prisma as any).symbolTemplate.findMany({
          where: { packageId: pkg.packageId },
          take: 5,
          select: { id: true, name: true, svgPath: true, categoryName: true },
        })

        return {
          packageId: pkg.packageId,
          packageName: pkg.packageName,
          symbolCount: pkg._count.id,
          categoryCount: categories.length,
          categories: categories.map((c: any) => ({
            categoryName: c.categoryName,
            symbolCount: c._count.id,
          })),
          previews,
        }
      })
    )

    return NextResponse.json({ packages: result })
  } catch (error: any) {
    console.error('Error fetching templates:', error)
    // Return empty packages list on DB schema mismatch so UI doesn't crash
    if (error?.message?.includes('symbol_templates') || error?.code === 'P2021') {
      return NextResponse.json({ packages: [] })
    }
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}
