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

const createTenantSchema = z.object({
  name: z.string().min(1).max(200),
  slug: z.string().min(1).max(100).regex(/^[a-z0-9-]+$/),
  description: z.string().optional(),
})

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

    const tenants = await (prisma as any).tenant.findMany({
      orderBy: { createdAt: 'desc' },
      include: {
        _count: {
          select: { memberships: true, projects: true },
        },
      },
    })
    return NextResponse.json({ tenants })
  } catch (error) {
    console.error('Error fetching tenants:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}

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

    const body = await req.json()
    const data = createTenantSchema.parse(body)

    const existing = await (prisma as any).tenant.findUnique({ where: { slug: data.slug } })
    if (existing) {
      return NextResponse.json({ error: 'Slug bereits vergeben' }, { status: 400 })
    }

    const tenant = await (prisma as any).tenant.create({
      data: {
        name: data.name,
        slug: data.slug,
        description: data.description,
      },
    })

    return NextResponse.json({ tenant }, { status: 201 })
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: 'Ungültige Daten' }, { status: 400 })
    }
    console.error('Error creating tenant:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}
