/**
 * Community Stats API
 *
 * Liefert Statistiken für das Community Inbox Dashboard.
 *
 * GET /api/community/stats
 */

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { createSafeLogger } from '@/lib/security'
import { hasCommunityApiAccess } from '@/lib/communityAccess'

const logger = createSafeLogger('API:CommunityStats')

export async function GET(req: NextRequest) {
  try {
    const payload = await getPayload({ config })

    // Authentifizierung prüfen
    const { user } = await payload.auth({ headers: req.headers })

    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const typedUser = user as { id: number }

    // Community-Zugriff prüfen
    if (!hasCommunityApiAccess(user as any, 'viewer')) {
      logger.warn('Access denied for stats', { userId: typedUser.id })
      return NextResponse.json({ error: 'Access denied' }, { status: 403 })
    }

    // Parallele Abfragen für bessere Performance
    const [newCount, urgentCount, waitingCount, todayCount, sentimentStats] = await Promise.all([
      // Neue Interaktionen
      payload.count({
        collection: 'community-interactions',
        where: { status: { equals: 'new' } },
      }),
      // Dringende Interaktionen
      payload.count({
        collection: 'community-interactions',
        where: {
          and: [
            { status: { not_equals: 'resolved' } },
            { status: { not_equals: 'archived' } },
            { status: { not_equals: 'spam' } },
            { priority: { equals: 'urgent' } },
          ],
        },
      }),
      // Wartende Interaktionen
      payload.count({
        collection: 'community-interactions',
        where: { status: { equals: 'waiting' } },
      }),
      // Heute eingegangen
      payload.count({
        collection: 'community-interactions',
        where: {
          createdAt: {
            greater_than_equal: new Date(new Date().setHours(0, 0, 0, 0)).toISOString(),
          },
        },
      }),
      // Sentiment-Verteilung (nur unerledigte)
      Promise.all([
        payload.count({
          collection: 'community-interactions',
          where: {
            and: [
              { status: { not_equals: 'resolved' } },
              { status: { not_equals: 'archived' } },
              { 'analysis.sentiment': { equals: 'positive' } },
            ],
          },
        }),
        payload.count({
          collection: 'community-interactions',
          where: {
            and: [
              { status: { not_equals: 'resolved' } },
              { status: { not_equals: 'archived' } },
              { 'analysis.sentiment': { equals: 'neutral' } },
            ],
          },
        }),
        payload.count({
          collection: 'community-interactions',
          where: {
            and: [
              { status: { not_equals: 'resolved' } },
              { status: { not_equals: 'archived' } },
              { 'analysis.sentiment': { equals: 'negative' } },
            ],
          },
        }),
      ]),
    ])

    const stats = {
      new: newCount.totalDocs,
      urgent: urgentCount.totalDocs,
      waiting: waitingCount.totalDocs,
      today: todayCount.totalDocs,
      sentiment: {
        positive: sentimentStats[0].totalDocs,
        neutral: sentimentStats[1].totalDocs,
        negative: sentimentStats[2].totalDocs,
      },
    }

    return NextResponse.json(stats)
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    logger.error('Stats error:', { error: errorMessage })
    return NextResponse.json({ error: errorMessage }, { status: 500 })
  }
}

export const dynamic = 'force-dynamic'
