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

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

    const formData = await req.formData()
    const file = formData.get('logo') as File
    if (!file) {
      return NextResponse.json({ error: 'Keine Datei hochgeladen' }, { status: 400 })
    }

    // Validate file type
    const validTypes = ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp']
    if (!validTypes.includes(file.type)) {
      return NextResponse.json({ error: 'Ungültiges Dateiformat. Erlaubt: PNG, JPEG, SVG, WebP' }, { status: 400 })
    }

    // Max 2MB
    if (file.size > 2 * 1024 * 1024) {
      return NextResponse.json({ error: 'Datei zu gross (max. 2 MB)' }, { status: 400 })
    }

    const buffer = Buffer.from(await file.arrayBuffer())
    const ext = file.name.split('.').pop() || 'png'
    const fileKey = `logos/tenant-${params.id}.${ext}`

    await uploadFile(fileKey, buffer, file.type)

    // Store fileKey for proxy-based serving, logoUrl for backward compat
    const logoServeUrl = `/api/admin/tenants/${params.id}/logo/serve`
    await (prisma as any).tenant.update({
      where: { id: params.id },
      data: { logoFileKey: fileKey, logoUrl: logoServeUrl },
    })

    return NextResponse.json({ logoUrl: logoServeUrl })
  } catch (error) {
    console.error('Logo upload error:', error)
    return NextResponse.json({ error: 'Upload fehlgeschlagen' }, { status: 500 })
  }
}

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

    // Get current logo
    const tenant = await (prisma as any).tenant.findUnique({ where: { id: params.id } })
    if (tenant?.logoUrl) {
      try {
        const urlParts = tenant.logoUrl.split('/')
        const fileKey = `logos/${urlParts[urlParts.length - 1]}`
        await deleteFile(fileKey)
      } catch {}
    }

    await (prisma as any).tenant.update({
      where: { id: params.id },
      data: { logoUrl: null },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Logo delete error:', error)
    return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 })
  }
}
