import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { checkAdminAuth } from '@/lib/auth-check'

// GET /api/admin/orders - Get orders with optional pagination (Admin only)
// Query params: ?limit=50&offset=0 (default: no limit, all orders)
export async function GET(request: Request) {
  const authError = await checkAdminAuth()
  if (authError) return authError

  try {
    const { searchParams } = new URL(request.url)
    const limit = searchParams.get('limit') ? parseInt(searchParams.get('limit')!) : undefined
    const offset = searchParams.get('offset') ? parseInt(searchParams.get('offset')!) : 0

    const orders = await prisma.order.findMany({
      include: {
        items: {
          include: {
            product: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
      take: limit, // undefined = no limit (backwards compatible)
      skip: offset,
    })

    // Also return total count for pagination UI
    const total = await prisma.order.count()

    return NextResponse.json({
      orders,
      total,
      limit: limit || null,
      offset,
    })
  } catch (error) {
    console.error('Error fetching orders:', error)
    return NextResponse.json({ error: 'Failed to fetch orders' }, { status: 500 })
  }
}
