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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    const olt = await db.oLTDevice.findUnique({
      where: { id },
      include: {
        onus: {
          include: {
            user: { select: { id: true, name: true, email: true, status: true } },
          },
          orderBy: [{ slot: 'asc' }, { port: 'asc' }],
        },
      },
    })

    if (!olt) {
      return NextResponse.json(
        { success: false, error: 'OLT device not found' },
        { status: 404 }
      )
    }

    const onuStatusCounts = {
      online: olt.onus.filter((o) => o.status === 'ONLINE').length,
      offline: olt.onus.filter((o) => o.status === 'OFFLINE').length,
      provisioning: olt.onus.filter((o) => o.status === 'PROVISIONING').length,
      faulty: olt.onus.filter((o) => o.status === 'FAULTY').length,
    }

    return NextResponse.json({
      success: true,
      data: {
        ...olt,
        onuStatusCounts,
      },
    })
  } 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 PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()

    const existing = await db.oLTDevice.findUnique({ where: { id } })
    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'OLT device not found' },
        { status: 404 }
      )
    }

    const { createdAt, updatedAt, onus, ...updateData } = body as Record<string, unknown>

    const olt = await db.oLTDevice.update({
      where: { id },
      data: updateData,
      include: {
        _count: {
          select: {
            onus: true,
            onusOnline: { where: { status: 'ONLINE' } },
          },
        },
      },
    })

    return NextResponse.json({ success: true, data: olt })
  } 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 DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    const existing = await db.oLTDevice.findUnique({
      where: { id },
      include: { _count: { select: { onus: true } } },
    })

    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'OLT device not found' },
        { status: 404 }
      )
    }

    if (existing._count.onus > 0) {
      return NextResponse.json(
        { success: false, error: 'Cannot delete OLT with associated ONUs' },
        { status: 400 }
      )
    }

    await db.oLTDevice.delete({ where: { id } })

    return NextResponse.json({
      success: true,
      message: 'OLT device deleted successfully',
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
