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 onu = await db.oNU.findUnique({
      where: { id },
      include: {
        olt: true,
        user: { select: { id: true, name: true, email: true, phone: true, status: true, area: true } },
      },
    })

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

    return NextResponse.json({ success: true, data: onu })
  } 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.oNU.findUnique({ where: { id } })
    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'ONU not found' },
        { status: 404 }
      )
    }

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

    const onu = await db.oNU.update({
      where: { id },
      data: updateData,
      include: {
        olt: { select: { id: true, name: true, ipAddress: true } },
        user: { select: { id: true, name: true, email: true } },
      },
    })

    return NextResponse.json({ success: true, data: onu })
  } 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.oNU.findUnique({ where: { id } })
    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'ONU not found' },
        { status: 404 }
      )
    }

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

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