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

const categorySchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().max(500).nullable().optional(),
})

export async function GET() {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    let where: any = {}
    if (user.role !== 'SERVER_ADMIN') {
      // TENANT_ADMIN: show global categories (tenantId=null) + their own tenant categories
      where = {
        OR: [
          { tenantId: null },
          ...(user.tenantId ? [{ tenantId: user.tenantId }] : []),
        ],
      }
    }
    // SERVER_ADMIN: show all categories (no filter)

    const categories = await db.iconCategory.findMany({
      where,
      orderBy: { sortOrder: 'asc' },
      include: {
        _count: { select: { icons: true } },
      },
    })

    return NextResponse.json({ categories })
  } catch (error) {
    console.error('Error fetching categories:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}

export async function POST(req: NextRequest) {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    const body = await req.json()
    const data = categorySchema.parse(body)

    const maxOrder = await db.iconCategory.aggregate({
      _max: { sortOrder: true },
    })

    // SERVER_ADMIN creates global categories; TENANT_ADMIN creates tenant-specific ones
    const isGlobal = user.role === 'SERVER_ADMIN'
    const tenantId = user.role === 'SERVER_ADMIN' ? null : (user.tenantId || null)

    const category = await db.iconCategory.create({
      data: {
        name: data.name,
        description: data.description,
        sortOrder: (maxOrder._max.sortOrder || 0) + 1,
        isGlobal,
        tenantId,
      } as any,
    })

    return NextResponse.json({ category }, { status: 201 })
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: 'Ungültige Daten' }, { status: 400 })
    }
    console.error('Error creating category:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}
