import { NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { prisma } from '@/lib/db'
import { uploadFile } from '@/lib/minio'
import { v4 as uuidv4 } from 'uuid'

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

    if (user.role === 'VIEWER') {
      return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
    }

    const formData = await request.formData()
    const file = formData.get('file') as File | null
    const name = formData.get('name') as string | null
    const categoryId = formData.get('categoryId') as string | null

    if (!file || !name || !categoryId) {
      return NextResponse.json(
        { error: 'Datei, Name und Kategorie sind erforderlich' },
        { status: 400 }
      )
    }

    const allowedTypes = ['image/png', 'image/svg+xml', 'image/jpeg', 'image/webp']
    if (!allowedTypes.includes(file.type)) {
      return NextResponse.json(
        { error: 'Nur PNG, SVG, JPEG und WebP Dateien sind erlaubt' },
        { status: 400 }
      )
    }

    const maxSize = 5 * 1024 * 1024 // 5MB
    if (file.size > maxSize) {
      return NextResponse.json(
        { error: 'Datei ist zu gross (max. 5MB)' },
        { status: 400 }
      )
    }

    const category = await prisma.iconCategory.findUnique({
      where: { id: categoryId },
    })

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

    const fileExtension = file.name.split('.').pop() || 'png'
    const fileKey = `icons/${user.id}/${uuidv4()}.${fileExtension}`
    
    const buffer = Buffer.from(await file.arrayBuffer())
    await uploadFile(fileKey, buffer, file.type)

    const iconAsset = await prisma.iconAsset.create({
      data: {
        name,
        categoryId,
        ownerId: user.id,
        fileKey,
        mimeType: file.type,
        isSystem: false,
      },
    })

    return NextResponse.json({ icon: iconAsset }, { status: 201 })
  } catch (error) {
    console.error('Error uploading icon:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
