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

// Toggle icon visibility for the current tenant (adds/removes from hiddenIconIds)
export async function POST(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = await getSession()
    if (!user || !isAdmin(user.role)) {
      return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
    }

    if (!user.tenantId) {
      return NextResponse.json({ error: 'Kein Mandant zugeordnet' }, { status: 400 })
    }

    const iconId = params.id

    // Get current tenant
    const tenant = await (prisma as any).tenant.findUnique({
      where: { id: user.tenantId },
      select: { hiddenIconIds: true },
    })

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

    const hiddenIds: string[] = tenant.hiddenIconIds || []
    const isHidden = hiddenIds.includes(iconId)

    // Toggle: if hidden, unhide; if visible, hide
    const updatedHiddenIds = isHidden
      ? hiddenIds.filter((id: string) => id !== iconId)
      : [...hiddenIds, iconId]

    await (prisma as any).tenant.update({
      where: { id: user.tenantId },
      data: { hiddenIconIds: updatedHiddenIds },
    })

    return NextResponse.json({
      success: true,
      isHidden: !isHidden,
      message: isHidden ? 'Symbol eingeblendet' : 'Symbol ausgeblendet',
    })
  } catch (error) {
    console.error('Error toggling icon visibility:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}
