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 area = await db.area.findUnique({
      where: { id },
      include: {
        users: {
          select: { id: true, name: true, email: true, status: true, connectionType: true },
          take: 50,
        },
        plans: true,
        _count: {
          select: {
            users: { where: { status: 'ACTIVE' } },
            plans: { where: { isActive: true } },
          },
        },
      },
    })

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

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

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

    // Check for code uniqueness if code is being updated
    if (updateData.code && updateData.code !== existing.code) {
      const codeExists = await db.area.findUnique({ where: { code: updateData.code as string } })
      if (codeExists) {
        return NextResponse.json(
          { success: false, error: 'Area code already exists' },
          { status: 409 }
        )
      }
    }

    const area = await db.area.update({
      where: { id },
      data: updateData,
      include: {
        _count: { select: { users: true, plans: true } },
      },
    })

    return NextResponse.json({ success: true, data: area })
  } 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.area.findUnique({
      where: { id },
      include: {
        _count: { select: { users: true, plans: true } },
      },
    })

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

    if (existing._count.users > 0 || existing._count.plans > 0) {
      return NextResponse.json(
        { success: false, error: 'Cannot delete area with associated users or plans' },
        { status: 400 }
      )
    }

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

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