import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getSession } from '@/lib/auth'

export async function GET() {
  try {
    const user = await getSession()

    // Filter categories: global (tenantId=null) + tenant-specific
    const categoryWhere: any = user?.tenantId
      ? { OR: [{ tenantId: null }, { tenantId: user.tenantId }] }
      : {}

    const categories = await (prisma as any).iconCategory.findMany({
      where: categoryWhere,
      orderBy: { sortOrder: 'asc' },
      include: {
        icons: {
          where: user?.tenantId
            ? { isActive: true, OR: [{ tenantId: null }, { tenantId: user.tenantId }] }
            : { isActive: true, tenantId: null },
          orderBy: { name: 'asc' },
        },
      },
    })

    // Get tenant's hidden icon IDs (legacy)
    let hiddenIconIds: string[] = []
    if (user?.tenantId) {
      const tenant = await (prisma as any).tenant.findUnique({
        where: { id: user.tenantId },
        select: { hiddenIconIds: true },
      })
      hiddenIconIds = tenant?.hiddenIconIds || []
    }

    const categoriesWithUrls = categories.map((cat: any) => ({
      ...cat,
      icons: cat.icons
        .filter((icon: any) => !hiddenIconIds.includes(icon.id))
        .map((icon: any) => ({
          ...icon,
          url: `/api/icons/${icon.id}/image`,
        })),
    }))

    // Get tenant's custom symbol collection (with custom names)
    let mySymbols: any[] = []
    if (user?.tenantId) {
      const tenantSymbols = await (prisma as any).tenantSymbol.findMany({
        where: { tenantId: user.tenantId },
        include: { icon: { select: { id: true, name: true, mimeType: true, iconType: true } } },
        orderBy: { sortOrder: 'asc' },
      })
      mySymbols = tenantSymbols.map((ts: any) => ({
        id: ts.icon.id,
        tenantSymbolId: ts.id,
        name: ts.customName || ts.icon.name,
        customName: ts.customName,
        mimeType: ts.icon.mimeType,
        iconType: ts.icon.iconType,
        url: `/api/icons/${ts.icon.id}/image`,
      }))
    }

    return NextResponse.json({ categories: categoriesWithUrls, mySymbols })
  } catch (error) {
    console.error('Error fetching icons:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
