/**
 * Community Analytics Sentiment Trend API
 *
 * Liefert Sentiment-Zeitreihe für Charts.
 *
 * GET /api/community/analytics/sentiment-trend
 * Query: period (7d|30d|90d), channel (all|id), granularity (day|week)
 */

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

const logger = createSafeLogger('API:SentimentTrend')

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'
    let granularity = searchParams.get('granularity')

    // Auto-determine granularity based on period
    if (!granularity) {
      granularity = period === '90d' ? 'week' : 'day'
    }

    const payload = await getPayload({ config })

    // Auth check
    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 range
    const now = new Date()
    const days = period === '7d' ? 7 : period === '90d' ? 90 : 30
    const periodStart = subDays(now, days)

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

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

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

    // Generate date buckets
    const intervals =
      granularity === 'week'
        ? eachWeekOfInterval({ start: periodStart, end: now })
        : eachDayOfInterval({ start: periodStart, end: now })

    // Aggregate by date
    const data = intervals.map((date) => {
      const dateKey = format(date, 'yyyy-MM-dd')
      const nextDate =
        granularity === 'week' ? subDays(date, -7) : subDays(date, -1)

      const dayInteractions = interactions.docs.filter((i) => {
        const pubDate = new Date(i.publishedAt as string)
        return pubDate >= date && pubDate < nextDate
      })

      const sentiments = {
        positive: dayInteractions.filter((i) => i.analysis?.sentiment === 'positive').length,
        neutral: dayInteractions.filter((i) => i.analysis?.sentiment === 'neutral').length,
        negative: dayInteractions.filter((i) => i.analysis?.sentiment === 'negative').length,
        question: dayInteractions.filter((i) => i.analysis?.sentiment === 'question').length,
        gratitude: dayInteractions.filter((i) => i.analysis?.sentiment === 'gratitude').length,
        frustration: dayInteractions.filter((i) => i.analysis?.sentiment === 'frustration').length,
      }

      const scores = dayInteractions
        .filter((i) => i.analysis?.sentimentScore != null)
        .map((i) => i.analysis!.sentimentScore as number)

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

      return {
        date: dateKey,
        ...sentiments,
        avgScore,
        total: dayInteractions.length,
      }
    })

    return NextResponse.json({ data })
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    logger.error('Sentiment trend error:', { error: errorMessage })
    return NextResponse.json({ error: 'Failed to fetch sentiment trend' }, { status: 500 })
  }
}

export const dynamic = 'force-dynamic'
