/**
 * Community Analytics Overview API
 *
 * Liefert KPI-Übersicht für das Analytics Dashboard.
 *
 * GET /api/community/analytics/overview
 * Query: period (7d|30d|90d), channel (all|id)
 */

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

const logger = createSafeLogger('API:AnalyticsOverview')

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const period = searchParams.get('period') || '30d'
    const channelId = searchParams.get('channel') || 'all'

    const payload = await getPayload({ config })

    // Authentifizierung prüfen
    const { user } = await payload.auth({ headers: request.headers })
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    if (!hasCommunityApiAccess(user as any, 'viewer')) {
      return NextResponse.json({ error: 'Access denied' }, { status: 403 })
    }

    // Calculate date ranges
    const now = new Date()
    let periodStart: Date
    let previousPeriodStart: Date
    let previousPeriodEnd: Date

    switch (period) {
      case '7d':
        periodStart = subDays(now, 7)
        previousPeriodStart = subDays(now, 14)
        previousPeriodEnd = subDays(now, 7)
        break
      case '90d':
        periodStart = subDays(now, 90)
        previousPeriodStart = subDays(now, 180)
        previousPeriodEnd = subDays(now, 90)
        break
      default: // 30d
        periodStart = subDays(now, 30)
        previousPeriodStart = subDays(now, 60)
        previousPeriodEnd = subDays(now, 30)
    }

    // Build where clause
    const baseWhere: any = {
      publishedAt: {
        greater_than_equal: periodStart.toISOString(),
      },
    }

    if (channelId !== 'all') {
      baseWhere.socialAccount = { equals: parseInt(channelId, 10) }
    }

    // Fetch current period data
    const currentInteractions = await payload.find({
      collection: 'community-interactions',
      where: baseWhere,
      limit: 10000,
    })

    // Calculate metrics
    const docs = currentInteractions.docs
    const total = docs.length
    const newCount = docs.filter((i) => i.status === 'new').length
    const repliedCount = docs.filter((i) =>
      ['replied', 'resolved'].includes(i.status as string),
    ).length

    const responseRate = total > 0 ? (repliedCount / total) * 100 : 0

    // Calculate average response time
    const responseTimes = docs
      .filter((i) => i.response?.sentAt && i.publishedAt)
      .map((i) =>
        differenceInHours(
          new Date(i.response!.sentAt as string),
          new Date(i.publishedAt as string),
        ),
      )

    const avgResponseTime =
      responseTimes.length > 0
        ? responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length
        : 0

    // Calculate sentiment (normalize confidence from 0-100 to 0-1)
    const sentimentScores = docs
      .filter((i) => i.analysis?.sentimentScore != null)
      .map((i) => {
        const score = i.analysis!.sentimentScore as number
        const confidence = ((i.analysis!.confidence as number) || 100) / 100
        return score * confidence
      })

    const avgSentiment =
      sentimentScores.length > 0
        ? sentimentScores.reduce((a, b) => a + b, 0) / sentimentScores.length
        : 0

    // Sentiment distribution (all 6 types)
    const sentimentDistribution = {
      positive: docs.filter((i) => i.analysis?.sentiment === 'positive').length,
      neutral: docs.filter((i) => i.analysis?.sentiment === 'neutral').length,
      negative: docs.filter((i) => i.analysis?.sentiment === 'negative').length,
      question: docs.filter((i) => i.analysis?.sentiment === 'question').length,
      gratitude: docs.filter((i) => i.analysis?.sentiment === 'gratitude').length,
      frustration: docs.filter((i) => i.analysis?.sentiment === 'frustration').length,
    }

    // Count flags
    const medicalQuestions = docs.filter((i) => i.flags?.isMedicalQuestion).length
    const escalations = docs.filter((i) => i.flags?.requiresEscalation).length

    // Fetch previous period for comparison
    const previousWhere: any = {
      publishedAt: {
        greater_than_equal: previousPeriodStart.toISOString(),
        less_than: previousPeriodEnd.toISOString(),
      },
    }

    if (channelId !== 'all') {
      previousWhere.socialAccount = { equals: parseInt(channelId, 10) }
    }

    const previousInteractions = await payload.find({
      collection: 'community-interactions',
      where: previousWhere,
      limit: 10000,
    })

    const prevDocs = previousInteractions.docs
    const prevTotal = prevDocs.length
    const prevRepliedCount = prevDocs.filter((i) =>
      ['replied', 'resolved'].includes(i.status as string),
    ).length
    const prevResponseRate = prevTotal > 0 ? (prevRepliedCount / prevTotal) * 100 : 0

    const prevSentimentScores = prevDocs
      .filter((i) => i.analysis?.sentimentScore != null)
      .map((i) => {
        const score = i.analysis!.sentimentScore as number
        const confidence = ((i.analysis!.confidence as number) || 100) / 100
        return score * confidence
      })

    const prevAvgSentiment =
      prevSentimentScores.length > 0
        ? prevSentimentScores.reduce((a, b) => a + b, 0) / prevSentimentScores.length
        : 0

    // Calculate comparisons
    const totalChange = prevTotal > 0 ? ((total - prevTotal) / prevTotal) * 100 : 0
    const responseRateChange = responseRate - prevResponseRate
    const sentimentChange = avgSentiment - prevAvgSentiment

    return NextResponse.json({
      period,
      totalInteractions: total,
      newInteractions: newCount,
      responseRate,
      avgResponseTimeHours: avgResponseTime,
      avgSentimentScore: avgSentiment,
      medicalQuestions,
      escalations,
      sentimentDistribution,
      comparison: {
        totalInteractions: Math.round(totalChange),
        responseRate: responseRateChange,
        avgSentimentScore: sentimentChange,
      },
    })
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    logger.error('Analytics overview error:', { error: errorMessage })
    return NextResponse.json({ error: 'Failed to fetch analytics' }, { status: 500 })
  }
}

export const dynamic = 'force-dynamic'
