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 search = searchParams.get('search')

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

    if (status) where.status = status
    if (search) {
      where.OR = [
        { name: { contains: search } },
        { ipAddress: { contains: search } },
        { model: { contains: search } },
      ]
    }

    const [olts, total] = await Promise.all([
      db.oLTDevice.findMany({
        where,
        include: {
          _count: {
            select: {
              onus: true,
              onusOnline: { where: { status: 'ONLINE' } },
            },
          },
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.oLTDevice.count({ where }),
    ])

    return NextResponse.json({
      success: true,
      data: {
        olts,
        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 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { name, ipAddress, username, password, model, firmware, portCount, status } = body

    if (!name || !ipAddress) {
      return NextResponse.json(
        { success: false, error: 'Name and IP address are required' },
        { status: 400 }
      )
    }

    const olt = await db.oLTDevice.create({
      data: {
        name,
        ipAddress,
        username: username || '',
        password: password || '',
        model: model || '',
        firmware: firmware || '',
        portCount: portCount || 16,
        status: status || 'ONLINE',
      },
    })

    return NextResponse.json({ success: true, data: olt }, { status: 201 })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
