import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

export async function GET(request: Request) {
  try {
    const { auth } = await import('@/lib/auth')
    const { isAdmin } = await import('@/lib/admin')

    const session = await auth()
    if (!session?.user?.email || !isAdmin(session.user.email)) {
      return NextResponse.json(
        { success: false, error: 'Admin access required' },
        { status: 403 }
      )
    }

    // Get query parameters
    const { searchParams } = new URL(request.url)
    const startDate = searchParams.get('startDate')
    const endDate = searchParams.get('endDate')

    // Set default date range if not provided
    const start = startDate ? new Date(startDate) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
    const end = endDate ? new Date(endDate + 'T23:59:59.999Z') : new Date()

    // Get visitor data for the date range
    const visitors = await prisma.visitor.findMany({
      where: {
        visitedAt: {
          gte: start,
          lte: end
        }
      },
      orderBy: {
        visitedAt: 'asc'
      }
    })

    // Group visitors by date and get unique IPs per day
    const dailyVisitors = visitors.reduce((acc: any[], visitor) => {
      const date = visitor.visitedAt.toISOString().split('T')[0]
      const existingDay = acc.find(day => day.date === date)

      if (existingDay) {
        existingDay.visitors.push(visitor)
        if (!existingDay.ips.includes(visitor.ip)) {
          existingDay.ips.push(visitor.ip)
        }
      } else {
        acc.push({
          date,
          visitors: [visitor],
          ips: [visitor.ip],
          paths: [visitor.path]
        })
      }

      return acc
    }, [])

    // Get top page for each day
    const pageVisitsByDay = visitors.reduce((acc: any, visitor) => {
      const date = visitor.visitedAt.toISOString().split('T')[0]
      const path = visitor.path || '/'

      if (!acc[date]) {
        acc[date] = {}
      }

      if (!acc[date][path]) {
        acc[date][path] = 0
      }

      acc[date][path]++

      return acc
    }, {})

    // Format the response
    const formattedData = dailyVisitors.map(day => {
      const pageData = pageVisitsByDay[day.date] || {}
      const topPagePath = Object.entries(pageData)
        .sort(([, a], [, b]) => (b as number) - (a as number))[0]

      return {
        date: day.date,
        visitors: day.visitors.length,
        uniqueIps: day.ips.length,
        topPage: topPagePath ? {
          path: topPagePath[0],
          visits: topPagePath[1] as number
        } : undefined
      }
    })

    return NextResponse.json({
      success: true,
      data: formattedData
    })

  } catch (error) {
    console.error('Visitor data error:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to fetch visitor data' },
      { status: 500 }
    )
  }
}