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

// GET: Fetch dictionary words (global + tenant-specific merged)
export async function GET(req: NextRequest) {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    // Global words
    const globalWords = await (prisma as any).dictionaryEntry.findMany({
      where: { scope: 'GLOBAL' },
      orderBy: { word: 'asc' },
    })

    // Tenant words (if user has a tenant)
    let tenantWords: any[] = []
    if (user.tenantId) {
      tenantWords = await (prisma as any).dictionaryEntry.findMany({
        where: { scope: 'TENANT', tenantId: user.tenantId },
        orderBy: { word: 'asc' },
      })
    }

    // Merge: tenant words override global (by word)
    const tenantWordSet = new Set(tenantWords.map((w: any) => w.word.toLowerCase()))
    const merged = [
      ...tenantWords.map((w: any) => ({ ...w, source: 'tenant' })),
      ...globalWords
        .filter((w: any) => !tenantWordSet.has(w.word.toLowerCase()))
        .map((w: any) => ({ ...w, source: 'global' })),
    ].sort((a, b) => a.word.localeCompare(b.word, 'de'))

    return NextResponse.json({ words: merged })
  } catch (error) {
    console.error('Error fetching dictionary:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}

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

    const body = await req.json()
    const { word, scope } = body

    if (!word?.trim()) {
      return NextResponse.json({ error: 'Wort erforderlich' }, { status: 400 })
    }

    // Only SERVER_ADMIN can add global words
    if (scope === 'GLOBAL' && user.role !== 'SERVER_ADMIN') {
      return NextResponse.json({ error: 'Nur Server-Admin kann globale Wörter hinzufügen' }, { status: 403 })
    }

    const tenantId = scope === 'TENANT' ? user.tenantId : null

    const entry = await (prisma as any).dictionaryEntry.create({
      data: {
        word: word.trim(),
        scope: scope || 'GLOBAL',
        tenantId,
      },
    })

    return NextResponse.json(entry)
  } catch (error: any) {
    if (error?.code === 'P2002') {
      return NextResponse.json({ error: 'Wort existiert bereits' }, { status: 409 })
    }
    console.error('Error adding dictionary word:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
