import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { UserStatus } from '@prisma/client'

/**
 * GET /api/v1/admin/customers/[id]
 * Get customer details with orders and subscriptions
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id: customerId } = await params

    const customer = await prisma.user.findUnique({
      where: { id: customerId },
      include: {
        subscriptions: {
          orderBy: { createdAt: 'desc' },
        },
        orders: {
          orderBy: { createdAt: 'desc' },
          include: {
            _count: {
              select: { provisioningLogs: true },
            },
          },
        },
        tokenUsage: {
          orderBy: { createdAt: 'desc' },
          take: 100,
        },
        _count: {
          select: {
            orders: true,
            subscriptions: true,
            tokenUsage: true,
          },
        },
      },
    })

    if (!customer) {
      return NextResponse.json({ error: 'Customer not found' }, { status: 404 })
    }

    // Calculate total token usage
    const totalTokensUsed = customer.tokenUsage.reduce(
      (acc, usage) => acc + usage.tokensInput + usage.tokensOutput,
      0
    )

    // Get current subscription's token limit
    const currentSubscription = customer.subscriptions[0]
    const tokenLimit = currentSubscription?.tokenLimit || 0

    return NextResponse.json({
      ...customer,
      totalTokensUsed,
      tokenLimit,
    })
  } catch (error) {
    console.error('Error getting customer:', error)
    return NextResponse.json(
      { error: 'Failed to get customer' },
      { status: 500 }
    )
  }
}

/**
 * PATCH /api/v1/admin/customers/[id]
 * Update customer details
 */
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id: customerId } = await params
    const body = await request.json()

    // Validate customer exists
    const existingCustomer = await prisma.user.findUnique({
      where: { id: customerId },
    })

    if (!existingCustomer) {
      return NextResponse.json({ error: 'Customer not found' }, { status: 404 })
    }

    // Build update data
    const updateData: {
      name?: string
      company?: string
      status?: UserStatus
    } = {}

    if (body.name !== undefined) {
      updateData.name = body.name
    }

    if (body.company !== undefined) {
      updateData.company = body.company
    }

    if (body.status !== undefined) {
      updateData.status = body.status as UserStatus
    }

    const customer = await prisma.user.update({
      where: { id: customerId },
      data: updateData,
      include: {
        subscriptions: {
          orderBy: { createdAt: 'desc' },
          take: 1,
        },
        _count: {
          select: {
            orders: true,
            subscriptions: true,
          },
        },
      },
    })

    return NextResponse.json(customer)
  } catch (error) {
    console.error('Error updating customer:', error)
    return NextResponse.json(
      { error: 'Failed to update customer' },
      { status: 500 }
    )
  }
}

/**
 * DELETE /api/v1/admin/customers/[id]
 * Delete a customer and all related records (orders, subscriptions, token usage)
 * Does NOT touch any actual servers - just removes from Hub database
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id: customerId } = await params

    // Find existing customer with their orders
    const existingCustomer = await prisma.user.findUnique({
      where: { id: customerId },
      include: {
        orders: {
          include: {
            dnsVerification: true,
          },
        },
      },
    })

    if (!existingCustomer) {
      return NextResponse.json({ error: 'Customer not found' }, { status: 404 })
    }

    // Note: Staff users are in a separate table, so this endpoint only handles customers

    // Delete in correct order to respect foreign key constraints
    // 1. For each order, delete related records
    for (const order of existingCustomer.orders) {
      // Delete DNS records and verification
      if (order.dnsVerification) {
        await prisma.dnsRecord.deleteMany({
          where: { dnsVerificationId: order.dnsVerification.id },
        })
        await prisma.dnsVerification.delete({
          where: { id: order.dnsVerification.id },
        })
      }

      // Delete provisioning logs
      await prisma.provisioningLog.deleteMany({
        where: { orderId: order.id },
      })

      // Delete jobs
      await prisma.provisioningJob.deleteMany({
        where: { orderId: order.id },
      })
    }

    // 2. Delete all orders
    await prisma.order.deleteMany({
      where: { userId: customerId },
    })

    // 3. Delete subscriptions
    await prisma.subscription.deleteMany({
      where: { userId: customerId },
    })

    // 4. Delete token usage records
    await prisma.tokenUsage.deleteMany({
      where: { userId: customerId },
    })

    // 5. Delete the customer/user
    await prisma.user.delete({
      where: { id: customerId },
    })

    return NextResponse.json({
      success: true,
      message: `Customer ${existingCustomer.email} and all related records deleted`,
      deletedOrders: existingCustomer.orders.length,
    })
  } catch (error) {
    console.error('Error deleting customer:', error)
    return NextResponse.json(
      { error: 'Failed to delete customer' },
      { status: 500 }
    )
  }
}
