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

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

    // Tenant isolation check
    const projectCheck = await getProjectWithTenantCheck(params.id, user)
    if (!projectCheck) {
      return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
    }

    const { searchParams } = new URL(request.url)
    const format = searchParams.get('format') || 'json'

    const project = await (prisma as any).project.findUnique({
      where: { id: params.id },
      include: {
        features: true,
        owner: {
          select: { name: true },
        },
      },
    })

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

    if (format === 'geojson') {
      const geojson = {
        type: 'FeatureCollection',
        properties: {
          title: project.title,
          location: project.location,
          description: project.description,
          createdAt: project.createdAt,
          updatedAt: project.updatedAt,
          owner: project.owner?.name ?? null,
        },
        features: project.features.map((f: any) => ({
          type: 'Feature',
          id: f.id,
          geometry: f.geometry,
          properties: {
            type: f.type,
            ...f.properties as object,
          },
        })),
      }

      return new NextResponse(JSON.stringify(geojson, null, 2), {
        headers: {
          'Content-Type': 'application/geo+json',
          'Content-Disposition': `attachment; filename="${project.title.replace(/[^a-z0-9]/gi, '_')}.geojson"`,
        },
      })
    }

    // Default: return project data for client-side PDF/PNG generation
    return NextResponse.json({
      project: {
        ...project,
        features: project.features.map((f: any) => ({
          id: f.id,
          type: f.type,
          geometry: f.geometry,
          properties: f.properties,
        })),
      },
    })
  } catch (error) {
    console.error('Error exporting project:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
