import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { deleteFile } from '@/lib/minio'
import { getSession, isAdmin, isServerAdmin } from '@/lib/auth'
import { z } from 'zod'

const updateSchema = z.object({
  name: z.string().min(1).max(100).optional(),
  categoryId: z.string().uuid().optional(),
  iconType: z.enum(['STANDARD', 'RETTUNG', 'GEFAHRSTOFF', 'FEUER', 'WASSER', 'FAHRZEUG']).optional(),
  tags: z.array(z.string()).optional(),
  isActive: z.boolean().optional(),
})

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

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

    // TENANT_ADMIN can only edit their own icons
    if (!isServerAdmin(user.role)) {
      const existing = await (prisma as any).iconAsset.findUnique({ where: { id: params.id } })
      if (existing && existing.tenantId !== user.tenantId) {
        return NextResponse.json({ error: 'Keine Berechtigung für dieses Symbol' }, { status: 403 })
      }
    }

    const icon = await (prisma as any).iconAsset.update({
      where: { id: params.id },
      data: {
        ...(data.name && { name: data.name }),
        ...(data.categoryId && { categoryId: data.categoryId }),
        ...(data.iconType && { iconType: data.iconType }),
        ...(data.tags && { tags: data.tags }),
        ...(data.isActive !== undefined && { isActive: data.isActive }),
      },
      include: {
        category: true,
      },
    })

    return NextResponse.json({ icon })
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: 'Ungültige Daten' }, { status: 400 })
    }
    console.error('Error updating icon:', 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 || !isAdmin(user.role)) {
      return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
    }

    const icon = await (prisma as any).iconAsset.findUnique({
      where: { id: params.id },
    })

    if (!icon) {
      return NextResponse.json({ error: 'Icon nicht gefunden' }, { status: 404 })
    }

    // TENANT_ADMIN can only delete their own tenant icons, not global/system ones
    if (!isServerAdmin(user.role)) {
      if (!icon.tenantId || icon.tenantId !== user.tenantId) {
        return NextResponse.json({ error: 'Globale Symbole können nicht gelöscht werden. Sie können nur Ihre eigenen Symbole löschen.' }, { status: 403 })
      }
    }

    // Delete from MinIO if not a system icon
    if (icon.fileKey && !icon.fileKey.startsWith('system:') && !icon.isSystem) {
      try {
        await deleteFile(icon.fileKey)
      } catch (e) {
        console.error('Error deleting file from MinIO:', e)
      }
    }

    await (prisma as any).iconAsset.delete({
      where: { id: params.id },
    })

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