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

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

    const { searchParams } = new URL(request.url)
    const tenantId = searchParams.get('tenantId')

    const where: any = {}
    if (tenantId) where.tenantId = tenantId

    const projects = await (prisma as any).project.findMany({
      where,
      orderBy: { updatedAt: 'desc' },
      include: {
        owner: {
          select: { id: true, name: true, email: true },
        },
        tenant: {
          select: { id: true, name: true },
        },
        _count: {
          select: { features: true },
        },
      },
    })

    return NextResponse.json({ projects })
  } catch (error) {
    console.error('Error fetching admin projects:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
