import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { enterpriseClientService } from '@/lib/services/enterprise-client-service'
import { z } from 'zod'

interface RouteContext {
  params: Promise<{ id: string }>
}

const updateClientSchema = z.object({
  name: z.string().min(1).optional(),
  companyName: z.string().optional().nullable(),
  contactEmail: z.string().email().optional(),
  contactPhone: z.string().optional().nullable(),
  notes: z.string().optional().nullable(),
  isActive: z.boolean().optional()
})

/**
 * GET /api/v1/admin/enterprise-clients/[id]
 * Get enterprise client details with servers and stats overview
 */
export async function GET(
  request: NextRequest,
  context: RouteContext
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id } = await context.params

  try {
    const [client, statsOverview] = await Promise.all([
      enterpriseClientService.getClient(id),
      enterpriseClientService.getClientStatsOverview(id)
    ])

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

    return NextResponse.json({
      ...client,
      statsOverview
    })
  } catch (error) {
    console.error('Failed to get enterprise client:', error)
    return NextResponse.json(
      { error: 'Failed to get enterprise client' },
      { status: 500 }
    )
  }
}

/**
 * PATCH /api/v1/admin/enterprise-clients/[id]
 * Update enterprise client
 */
export async function PATCH(
  request: NextRequest,
  context: RouteContext
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id } = await context.params

  try {
    const body = await request.json()
    const validation = updateClientSchema.safeParse(body)

    if (!validation.success) {
      return NextResponse.json(
        { error: 'Validation failed', details: validation.error.flatten() },
        { status: 400 }
      )
    }

    // Check if client exists
    const existingClient = await enterpriseClientService.getClient(id)
    if (!existingClient) {
      return NextResponse.json({ error: 'Client not found' }, { status: 404 })
    }

    const client = await enterpriseClientService.updateClient(id, validation.data)
    return NextResponse.json(client)
  } catch (error) {
    console.error('Failed to update enterprise client:', error)
    return NextResponse.json(
      { error: 'Failed to update enterprise client' },
      { status: 500 }
    )
  }
}

/**
 * DELETE /api/v1/admin/enterprise-clients/[id]
 * Delete enterprise client
 */
export async function DELETE(
  request: NextRequest,
  context: RouteContext
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id } = await context.params

  try {
    // Check if client exists
    const existingClient = await enterpriseClientService.getClient(id)
    if (!existingClient) {
      return NextResponse.json({ error: 'Client not found' }, { status: 404 })
    }

    await enterpriseClientService.deleteClient(id)
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Failed to delete enterprise client:', error)
    return NextResponse.json(
      { error: 'Failed to delete enterprise client' },
      { status: 500 }
    )
  }
}
