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

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

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

    // Check permission: TENANT_ADMIN can only edit their own tenant categories
    const category = await db.iconCategory.findUnique({ where: { id: params.id } }) as any
    if (!category) return NextResponse.json({ error: 'Kategorie nicht gefunden' }, { status: 404 })

    if (user.role !== 'SERVER_ADMIN') {
      if (!category.tenantId || category.tenantId !== user.tenantId) {
        return NextResponse.json({ error: 'Keine Berechtigung für diese Kategorie' }, { status: 403 })
      }
    }

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

    const updated = await db.iconCategory.update({
      where: { id: params.id },
      data,
    })

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

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

    // Check permission: TENANT_ADMIN can only delete their own tenant categories
    const category = await db.iconCategory.findUnique({ where: { id: params.id } }) as any
    if (!category) return NextResponse.json({ error: 'Kategorie nicht gefunden' }, { status: 404 })

    // Global categories (isGlobal=true, tenantId=null) cannot be deleted
    if (category.isGlobal || (!category.tenantId && category.isSystem !== false)) {
      return NextResponse.json({ error: 'Globale Kategorien können nicht gelöscht werden. Blenden Sie sie stattdessen aus.' }, { status: 403 })
    }

    if (user.role !== 'SERVER_ADMIN') {
      if (!category.tenantId || category.tenantId !== user.tenantId) {
        return NextResponse.json({ error: 'Keine Berechtigung für diese Kategorie' }, { status: 403 })
      }
    }

    // Disconnect all icons from this category (set categoryId to null) so they are NOT deleted
    await db.$executeRawUnsafe(
      `UPDATE icon_assets SET "categoryId" = NULL WHERE "categoryId" = $1`,
      params.id
    )

    await db.iconCategory.delete({
      where: { id: params.id },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting category:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}
