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

export async function GET() {
  try {
    const supabase = await createServerSupabaseClient()
    const { data: { user: supabaseUser }, error: authError } = await supabase.auth.getUser()

    if (authError || !supabaseUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Check if user is admin
    const user = await prisma.user.findUnique({
      where: { id: supabaseUser.id },
      select: { isAdmin: true }
    })

    if (!user?.isAdmin) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    // Get statistics
    const [totalUsers, totalPrompts, sharedPrompts, publishedPrompts] = await Promise.all([
      prisma.user.count(),
      prisma.prompt.count(),
      prisma.prompt.count({
        where: { permissions: 'public' }
      }),
      prisma.prompt.count({
        where: { 
          permissions: 'public',
          visibility: 'published'
        }
      })
    ])

    return NextResponse.json({
      totalUsers,
      totalPrompts,
      sharedPrompts,
      publishedPrompts
    })

  } catch (error) {
    console.error('Error fetching admin stats:', error)
    return NextResponse.json(
      { error: 'Failed to fetch stats' },
      { status: 500 }
    )
  }
}