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

const createClientSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  companyName: z.string().optional(),
  contactEmail: z.string().email('Valid email is required'),
  contactPhone: z.string().optional(),
  notes: z.string().optional()
})

/**
 * GET /api/v1/admin/enterprise-clients
 * List all enterprise clients
 */
export async function GET() {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  try {
    const clients = await enterpriseClientService.getClients()
    return NextResponse.json(clients)
  } catch (error) {
    console.error('Failed to list enterprise clients:', error)
    return NextResponse.json(
      { error: 'Failed to list enterprise clients' },
      { status: 500 }
    )
  }
}

/**
 * POST /api/v1/admin/enterprise-clients
 * Create a new enterprise client
 */
export async function POST(request: NextRequest) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

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

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

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