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

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

    if (!user.tenantId) {
      return NextResponse.json({ tenant: null })
    }

    const tenant = await (prisma as any).tenant.findUnique({
      where: { id: user.tenantId },
      select: {
        id: true,
        name: true,
        slug: true,
        description: true,
        contactEmail: true,
        contactPhone: true,
        address: true,
        logoUrl: true,
        plan: true,
        subscriptionStatus: true,
        privacyAccepted: true,
        privacyAcceptedAt: true,
        adminAccessAccepted: true,
        createdAt: true,
        _count: {
          select: {
            memberships: true,
            projects: true,
          },
        },
      },
    })

    return NextResponse.json({ tenant })
  } catch (error: any) {
    console.error('[Tenant Info] Error:', error?.message)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}

export async function PATCH(req: NextRequest) {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
    if (user.role !== 'TENANT_ADMIN') return NextResponse.json({ error: 'Nur Admin' }, { status: 403 })
    if (!user.tenantId) return NextResponse.json({ error: 'Kein Mandant' }, { status: 400 })

    const body = await req.json()
    const { name, description, contactEmail, contactPhone, address } = body

    if (!name || !name.trim()) {
      return NextResponse.json({ error: 'Name darf nicht leer sein' }, { status: 400 })
    }

    const updated = await (prisma as any).tenant.update({
      where: { id: user.tenantId },
      data: {
        name: name.trim(),
        description: description || null,
        contactEmail: contactEmail || null,
        contactPhone: contactPhone || null,
        address: address || null,
      },
    })

    return NextResponse.json({ tenant: updated })
  } catch (error: any) {
    console.error('[Tenant Info PATCH] Error:', error?.message)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
