/**
 * Community Analytics Channel Comparison API
 *
 * Vergleicht Performance über alle Kanäle.
 *
 * GET /api/community/analytics/channel-comparison
 * Query: period (7d|30d|90d)
 */

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:ChannelComparison')

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

    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)

    // Fetch all active social accounts
    const accounts = await payload.find({
      collection: 'social-accounts',
      where: { isActive: { equals: true } },
      limit: 100,
      depth: 1, // Include platform relation
    })

    // Fetch all interactions for the period
    const interactions = await payload.find({
      collection: 'community-interactions',
      where: {
        publishedAt: { greater_than_equal: periodStart.toISOString() },
      },
      limit: 10000,
    })

    // Calculate metrics per channel
    const channels = accounts.docs.map((account) => {
      const accountId = account.id
      const channelInteractions = interactions.docs.filter(
        (i) =>
          (typeof i.socialAccount === 'object'
            ? i.socialAccount?.id
            : i.socialAccount) === accountId,
      )

      const total = channelInteractions.length
      const repliedCount = channelInteractions.filter((i) =>
        ['replied', 'resolved'].includes(i.status as string),
      ).length
      const responseRate = total > 0 ? (repliedCount / total) * 100 : 0

      // Average sentiment
      const sentimentScores = channelInteractions
        .filter((i) => i.analysis?.sentimentScore != null)
        .map((i) => i.analysis!.sentimentScore as number)

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

      // Average response time
      const responseTimes = channelInteractions
        .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

      // Top topics
      const topicCounts: Record<string, number> = {}
      channelInteractions.forEach((i) => {
        if (i.analysis?.topics && Array.isArray(i.analysis.topics)) {
          i.analysis.topics.forEach((t: { topic?: string | null }) => {
            if (t.topic) {
              topicCounts[t.topic] = (topicCounts[t.topic] || 0) + 1
            }
          })
        }
      })

      const topTopics = Object.entries(topicCounts)
        .sort(([, a], [, b]) => b - a)
        .slice(0, 5)
        .map(([topic]) => topic)

      // Get platform name
      const platformName =
        typeof account.platform === 'object'
          ? (account.platform as { name?: string })?.name || 'Unknown'
          : 'Unknown'

      return {
        id: account.id,
        name: account.displayName,
        platform: platformName,
        metrics: {
          totalInteractions: total,
          avgSentiment,
          responseRate,
          avgResponseTimeHours: avgResponseTime,
          topTopics,
        },
      }
    })

    // Sort by total interactions
    channels.sort((a, b) => b.metrics.totalInteractions - a.metrics.totalInteractions)

    return NextResponse.json({ channels })
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    logger.error('Channel comparison error:', { error: errorMessage })
    return NextResponse.json({ error: 'Failed to fetch channel comparison' }, { status: 500 })
  }
}

export const dynamic = 'force-dynamic'
