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

// POST: Upload a plan image for a project
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    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 project = await getProjectWithTenantCheck(id, user)
    if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })

    const formData = await req.formData()
    const file = formData.get('file') as File | null
    const boundsStr = formData.get('bounds') as string | null

    if (!file) {
      return NextResponse.json({ error: 'Keine Datei angegeben' }, { status: 400 })
    }

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

    // Delete old plan image if exists
    const p = project as any
    if (p.planImageKey) {
      try { await deleteFile(p.planImageKey) } catch {}
    }

    // Upload to MinIO
    const buffer = Buffer.from(await file.arrayBuffer())
    const ext = file.name.split('.').pop() || 'png'
    const fileKey = `plans/${id}/${Date.now()}.${ext}`
    await uploadFile(fileKey, buffer, file.type)

    // Parse bounds or use default (current map view)
    let bounds = null
    if (boundsStr) {
      try { bounds = JSON.parse(boundsStr) } catch {}
    }

    // Update project
    await (prisma as any).project.update({
      where: { id },
      data: {
        planImageKey: fileKey,
        planBounds: bounds,
      },
    })

    const url = await getFileUrl(fileKey)

    return NextResponse.json({
      success: true,
      planImageUrl: url,
      planImageKey: fileKey,
      planBounds: bounds,
    })
  } catch (error) {
    console.error('Error uploading plan image:', error)
    return NextResponse.json({ error: 'Fehler beim Hochladen' }, { status: 500 })
  }
}

// DELETE: Remove the plan image
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    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 project = await getProjectWithTenantCheck(id, user)
    if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })

    const p = project as any
    if (p.planImageKey) {
      try { await deleteFile(p.planImageKey) } catch {}
    }

    await (prisma as any).project.update({
      where: { id },
      data: { planImageKey: null, planBounds: null },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting plan image:', error)
    return NextResponse.json({ error: 'Fehler beim Löschen' }, { status: 500 })
  }
}

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

    const project = await getProjectWithTenantCheck(id, user)
    if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })

    const body = await req.json()
    if (!body.bounds) return NextResponse.json({ error: 'Bounds erforderlich' }, { status: 400 })

    await (prisma as any).project.update({
      where: { id },
      data: { planBounds: body.bounds },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error updating plan bounds:', error)
    return NextResponse.json({ error: 'Fehler beim Aktualisieren' }, { status: 500 })
  }
}
