import { NextResponse } from 'next/server'
import { PrismaClient } from '@/app/generated/prisma'
import { auth } from '@/auth'

export async function GET(request: Request) {
  const prisma = new PrismaClient()
  try {
    const session = await auth()
    const { searchParams } = new URL(request.url)
    const handleIdsParam = searchParams.get('handleIds')
    let handleIds: string[] | null = null
    if (handleIdsParam) {
      handleIds = handleIdsParam.split(',').map(s => s.trim()).filter(Boolean)
    }

    if (!handleIds) {
      if (!session?.user?.email) return NextResponse.json({ items: [] })
      const myHandles = await prisma.handle.findMany({
        where: { users: { some: { email: session.user.email } } },
        select: { id: true },
      })
      handleIds = myHandles.map(h => h.id)
    }

    const items: Array<{ handleId: string, videoCount: number, views: number }> = []
    for (const id of handleIds) {
      const videoCount = await prisma.content.count({ where: { handleId: id } })
      const agg = await prisma.contentDayView.aggregate({
        _sum: { views: true },
        where: { content: { handleId: id } },
      })
      items.push({ handleId: id, videoCount, views: Number(agg._sum.views ?? 0) })
    }

    return NextResponse.json({ items })
  } catch (e) {
    return NextResponse.json({ error: 'stats failed' }, { status: 500 })
  } finally {
    try { await prisma.$disconnect() } catch {}
  }
}


