import { db } from '@/lib/db'
import { NextRequest, NextResponse } from 'next/server'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const status = searchParams.get('status')
    const oltId = searchParams.get('oltId')
    const userId = searchParams.get('userId')
    const search = searchParams.get('search')

    const where: Record<string, unknown> = {}

    if (status) where.status = status
    if (oltId) where.oltId = oltId
    if (userId) where.userId = userId
    if (search) {
      where.OR = [
        { serialNumber: { contains: search } },
      ]
    }

    const [onus, total] = await Promise.all([
      db.oNU.findMany({
        where,
        include: {
          olt: { select: { id: true, name: true, ipAddress: true, status: true } },
          user: { select: { id: true, name: true, email: true, status: true } },
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.oNU.count({ where }),
    ])

    // Summary stats
    const statusCounts = await db.oNU.groupBy({
      by: ['status'],
      _count: true,
    })

    return NextResponse.json({
      success: true,
      data: {
        onus,
        statusCounts: statusCounts.map((s) => ({
          status: s.status,
          count: s._count,
        })),
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
