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

export async function GET(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 tenant = await (prisma as any).tenant.findUnique({
      where: { id: params.id },
      include: {
        memberships: {
          include: { user: { select: { id: true, email: true, name: true, role: true, createdAt: true, lastLoginAt: true } } },
          orderBy: { createdAt: 'asc' },
        },
        _count: { select: { projects: true, memberships: true } },
      },
    })

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

    return NextResponse.json({ tenant })
  } catch (error) {
    console.error('Error fetching tenant:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}

export async function PATCH(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 body = await req.json()
    const {
      name, description, isActive, contactEmail, contactPhone, address,
      plan, subscriptionStatus, trialEndsAt, subscriptionEndsAt,
      maxUsers, maxProjects, notes, logoUrl,
    } = body

    const tenant = await (prisma as any).tenant.update({
      where: { id: params.id },
      data: {
        ...(name !== undefined && { name }),
        ...(description !== undefined && { description }),
        ...(isActive !== undefined && { isActive }),
        ...(contactEmail !== undefined && { contactEmail }),
        ...(contactPhone !== undefined && { contactPhone }),
        ...(address !== undefined && { address }),
        ...(logoUrl !== undefined && { logoUrl }),
        ...(plan !== undefined && { plan }),
        ...(subscriptionStatus !== undefined && { subscriptionStatus }),
        ...(trialEndsAt !== undefined && { trialEndsAt: trialEndsAt ? new Date(trialEndsAt) : null }),
        ...(subscriptionEndsAt !== undefined && { subscriptionEndsAt: subscriptionEndsAt ? new Date(subscriptionEndsAt) : null }),
        ...(maxUsers !== undefined && { maxUsers }),
        ...(maxProjects !== undefined && { maxProjects }),
        ...(notes !== undefined && { notes }),
      },
    })

    return NextResponse.json({ tenant })
  } catch (error) {
    console.error('Error updating tenant:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { 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 })
    }

    await (prisma as any).tenant.delete({ where: { id: params.id } })
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting tenant:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}
