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

export async function GET() {
  try {
    const session = await auth()

    if (!session?.user?.email || !isAdmin(session.user.email)) {
      return NextResponse.json(
        { success: false, error: 'Admin only' },
        { status: 403 }
      )
    }

    // Debug: Check raw data in each table
    const debug = {
      // 1. Check short_links table
      shortLinksDebug: {
        total: await prisma.$queryRaw`SELECT COUNT(*) as count FROM short_links`,
        active: await prisma.$queryRaw`SELECT COUNT(*) as count FROM short_links WHERE deleted_at IS NULL`,
        samples: await prisma.$queryRaw`SELECT id, code, link, created_at, deleted_at FROM short_links LIMIT 3`
      },

      // 2. Check users table
      usersDebug: {
        total: await prisma.user.count(),
        samples: await prisma.user.findMany({ take: 3, select: { id: true, email: true, createdAt: true } })
      },

      // 3. Check microsites table
      micrositesDebug: {
        total: await prisma.microsite.count(),
        samples: await prisma.microsite.findMany({ take: 3, select: { id: true, slug: true, title: true, createdAt: true } })
      },

      // 4. Check visitors table
      visitorsDebug: {
        total: await prisma.visitor.count(),
        today: await prisma.visitor.count({
          where: { visitedAt: { gte: new Date(new Date().setHours(0,0,0,0)) } }
        }),
        thisWeek: await prisma.visitor.count({
          where: { visitedAt: { gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) } }
        }),
        uniqueIPs: await prisma.visitor.groupBy({ by: ['ip'], _count: true }).then(r => r.length),
        samples: await prisma.visitor.findMany({
          take: 5,
          select: { ip: true, path: true, visitedAt: true, userAgent: true }
        })
      },

      // 5. Check microsite_links for clicks
      micrositeLinksDebug: {
        total: await prisma.micrositeLink.count(),
        totalClicks: await prisma.micrositeLink.aggregate({ _sum: { clicks: true } }),
        samples: await prisma.micrositeLink.findMany({ take: 3, select: { id: true, label: true, clicks: true } })
      }
    }

    // Test the actual queries from stats API
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const last7Days = new Date(today)
    last7Days.setDate(last7Days.getDate() - 7)

    const realQueries = {
      shortLinksToday: await prisma.$queryRaw`SELECT COUNT(*) as count FROM short_links WHERE deleted_at IS NULL AND created_at >= ${today}`,
      shortLinksThisWeek: await prisma.$queryRaw`SELECT COUNT(*) as count FROM short_links WHERE deleted_at IS NULL AND created_at >= ${last7Days}`,
      usersToday: await prisma.user.count({ where: { createdAt: { gte: today } } }),
      usersThisWeek: await prisma.user.count({ where: { createdAt: { gte: last7Days } } }),
    }

    return NextResponse.json({
      success: true,
      data: {
        debug,
        realQueries,
        currentTime: new Date().toISOString(),
        today: today.toISOString(),
        last7Days: last7Days.toISOString()
      }
    })

  } catch (error) {
    console.error('Test stats error:', error)
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    )
  }
}