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 plan = await db.plan.findUnique({
      where: { id },
      include: {
        area: true,
        subscriptions: {
          where: { status: 'ACTIVE' },
          include: { user: { select: { id: true, name: true, email: true } } },
          take: 20,
        },
        _count: {
          select: {
            subscriptions: { where: { status: 'ACTIVE' } },
          },
        },
      },
    })

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

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

    const { createdAt, updatedAt, ...updateData } = body

    const plan = await db.plan.update({
      where: { id },
      data: updateData,
      include: { area: true },
    })

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

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

    if (existing._count.subscriptions > 0) {
      return NextResponse.json(
        { success: false, error: 'Cannot delete plan with active subscriptions' },
        { status: 400 }
      )
    }

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

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