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

/**
 * GET /api/v1/admin/servers
 * List all servers (orders with server credentials)
 */
export async function GET(request: NextRequest) {
  try {
    const session = await auth()

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

    const searchParams = request.nextUrl.searchParams
    const status = searchParams.get('status')
    const search = searchParams.get('search')
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '50')

    // Build where clause - only orders with serverIp are considered servers
    const where: Prisma.OrderWhereInput = {
      serverIp: { not: null },
    }

    // Filter by server status (derived from order status)
    if (status === 'online') {
      where.status = { in: [OrderStatus.FULFILLED, OrderStatus.EMAIL_CONFIGURED] }
    } else if (status === 'provisioning') {
      where.status = { in: [OrderStatus.PROVISIONING, OrderStatus.DNS_READY, OrderStatus.SERVER_READY] }
    } else if (status === 'offline') {
      where.status = OrderStatus.FAILED
    }

    // Search by domain or serverIp
    if (search) {
      where.OR = [
        { domain: { contains: search, mode: 'insensitive' } },
        { serverIp: { contains: search, mode: 'insensitive' } },
        { user: { name: { contains: search, mode: 'insensitive' } } },
        { user: { company: { contains: search, mode: 'insensitive' } } },
      ]
    }

    const [orders, total] = await Promise.all([
      prisma.order.findMany({
        where,
        select: {
          id: true,
          domain: true,
          tier: true,
          status: true,
          serverIp: true,
          sshPort: true,
          tools: true,
          createdAt: true,
          serverReadyAt: true,
          completedAt: true,
          user: {
            select: {
              id: true,
              name: true,
              email: true,
              company: true,
            },
          },
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      prisma.order.count({ where }),
    ])

    // Map orders to server format
    const servers = orders.map((order) => ({
      id: order.id,
      domain: order.domain,
      tier: order.tier,
      orderStatus: order.status,
      serverStatus: deriveServerStatus(order.status),
      serverIp: order.serverIp,
      sshPort: order.sshPort,
      tools: order.tools,
      createdAt: order.createdAt,
      serverReadyAt: order.serverReadyAt,
      completedAt: order.completedAt,
      customer: order.user,
    }))

    return NextResponse.json({
      servers,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    })
  } catch (error) {
    console.error('Error listing servers:', error)
    return NextResponse.json(
      { error: 'Failed to list servers' },
      { status: 500 }
    )
  }
}

function deriveServerStatus(orderStatus: OrderStatus): 'online' | 'provisioning' | 'offline' | 'pending' {
  switch (orderStatus) {
    case OrderStatus.FULFILLED:
    case OrderStatus.EMAIL_CONFIGURED:
      return 'online'
    case OrderStatus.PROVISIONING:
    case OrderStatus.DNS_READY:
    case OrderStatus.SERVER_READY:
      return 'provisioning'
    case OrderStatus.FAILED:
      return 'offline'
    default:
      return 'pending'
  }
}
