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

// GET: Fetch journal suggestions for a tenant (global + tenant dictionary merged)
export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ tenantId: string }> }
) {
  try {
    const { tenantId } = await params
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    // Fetch from new Dictionary model (global + tenant)
    const [globalWords, tenantWords, tenant] = await Promise.all([
      (prisma as any).dictionaryEntry.findMany({
        where: { scope: 'GLOBAL' },
        select: { word: true },
      }).catch(() => []),
      (prisma as any).dictionaryEntry.findMany({
        where: { scope: 'TENANT', tenantId },
        select: { word: true },
      }).catch(() => []),
      (prisma as any).tenant.findUnique({
        where: { id: tenantId },
        select: { journalSuggestions: true },
      }),
    ])

    // Merge: dictionary entries + legacy journalSuggestions (backward compat)
    const wordSet = new Set<string>()
    for (const w of tenantWords) wordSet.add(w.word)
    for (const w of globalWords) wordSet.add(w.word)
    if (tenant?.journalSuggestions) {
      for (const s of tenant.journalSuggestions) wordSet.add(s)
    }

    const suggestions = Array.from(wordSet).sort((a, b) => a.localeCompare(b, 'de'))
    return NextResponse.json({ suggestions })
  } catch (error) {
    console.error('Error fetching suggestions:', error)
    return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
  }
}

// PUT: Replace all journal suggestions for a tenant (admin only)
export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ tenantId: string }> }
) {
  try {
    const { tenantId } = await params
    const user = await getSession()
    if (!user || !isAdmin(user.role)) {
      return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
    }

    // TENANT_ADMIN can only edit their own tenant
    if (user.role !== 'SERVER_ADMIN' && user.tenantId !== tenantId) {
      return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
    }

    const body = await req.json()
    const suggestions: string[] = Array.isArray(body.suggestions)
      ? body.suggestions.filter((s: any) => typeof s === 'string' && s.trim()).map((s: string) => s.trim())
      : []

    await (prisma as any).tenant.update({
      where: { id: tenantId },
      data: { journalSuggestions: suggestions },
    })

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