import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { requireAuth } from '@/lib/api-auth'
import { Prisma } from '@prisma/client'

export async function GET(request: NextRequest) {
  try {
    const authResult = await requireAuth(['MANAGER'])(request)
    if ('error' in authResult) return authResult.error

    // Total reviews and average rating
    const aggregateResult = await db.review.aggregate({
      _count: true,
      _avg: { rating: true },
      where: { deletedAt: null },
    })

    const totalReviews = aggregateResult._count
    const averageRating = aggregateResult._avg.rating || 0

    // NPS calculation: % POSITIVE - % NEGATIVE
    const positiveCount = await db.review.count({ where: { sentiment: 'POSITIVE', deletedAt: null } })
    const negativeCount = await db.review.count({ where: { sentiment: 'NEGATIVE', deletedAt: null } })
    const nps = totalReviews > 0
      ? Math.round(((positiveCount - negativeCount) / totalReviews) * 100)
      : 0

    // Reviews by status
    const reviewsByStatus = {
      PENDING: await db.review.count({ where: { status: 'PENDING', deletedAt: null } }),
      ACKNOWLEDGED: await db.review.count({ where: { status: 'ACKNOWLEDGED', deletedAt: null } }),
      RESOLVED: await db.review.count({ where: { status: 'RESOLVED', deletedAt: null } }),
    }

    // Reviews by sentiment
    const reviewsBySentiment = {
      POSITIVE: positiveCount,
      NEGATIVE: negativeCount,
    }

    // Rating distribution (1-5)
    const ratingDistribution: Record<number, number> = {}
    for (let i = 1; i <= 5; i++) {
      ratingDistribution[i] = await db.review.count({ where: { rating: i, deletedAt: null } })
    }

    // Monthly trend (last 12 months)
    const now = new Date()
    const monthlyTrend = []
    for (let i = 11; i >= 0; i--) {
      const monthStart = new Date(now.getFullYear(), now.getMonth() - i, 1)
      const monthEnd = new Date(now.getFullYear(), now.getMonth() - i + 1, 0, 23, 59, 59, 999)

      const monthTotal = await db.review.count({
        where: {
          deletedAt: null,
          createdAt: { gte: monthStart, lte: monthEnd },
        },
      })

      const monthPositive = await db.review.count({
        where: {
          deletedAt: null,
          createdAt: { gte: monthStart, lte: monthEnd },
          sentiment: 'POSITIVE',
        },
      })

      const monthNegative = await db.review.count({
        where: {
          deletedAt: null,
          createdAt: { gte: monthStart, lte: monthEnd },
          sentiment: 'NEGATIVE',
        },
      })

      const monthAvg = await db.review.aggregate({
        _avg: { rating: true },
        where: {
          deletedAt: null,
          createdAt: { gte: monthStart, lte: monthEnd },
        },
      })

      monthlyTrend.push({
        month: monthStart.toISOString().slice(0, 7),
        total: monthTotal,
        positive: monthPositive,
        negative: monthNegative,
        avgRating: Math.round((monthAvg._avg.rating || 0) * 10) / 10,
      })
    }

    // Recent negative reviews (last 10)
    const recentNegativeReviews = await db.review.findMany({
      where: { sentiment: 'NEGATIVE', deletedAt: null },
      include: {
        customer: { select: { id: true, name: true, email: true } },
        assignedTo: { select: { id: true, name: true } },
      },
      orderBy: { createdAt: 'desc' },
      take: 10,
    })

    // Unattended over 24 hours (PENDING or ACKNOWLEDGED, created more than 24h ago)
    const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000)
    const unattendedOver24h = await db.review.count({
      where: {
        status: { in: ['PENDING', 'ACKNOWLEDGED'] },
        deletedAt: null,
        createdAt: { lte: twentyFourHoursAgo },
      },
    })

    return NextResponse.json({
      totalReviews,
      averageRating: Math.round(averageRating * 10) / 10,
      nps,
      reviewsByStatus,
      reviewsBySentiment,
      ratingDistribution,
      monthlyTrend,
      recentNegativeReviews,
      unattendedOver24h,
    })
  } catch (error) {
    console.error('Error en dashboard de gerente:', error)
    return NextResponse.json(
      { error: 'Error interno del servidor' },
      { status: 500 }
    )
  }
}
