import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { credentialService } from '@/lib/services/credential-service'
import { createPortainerClient } from '@/lib/services/portainer-client'

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

/**
 * GET /api/v1/admin/orders/[id]/portainer
 * Get Portainer credentials for an order (decrypted)
 */
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: orderId } = await context.params

  const order = await prisma.order.findUnique({
    where: { id: orderId },
    select: {
      id: true,
      serverIp: true,
      portainerUsername: true,
      portainerPasswordEnc: true,
      credentialsSyncedAt: true,
    },
  })

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

  // Construct Portainer URL from server IP (Portainer is accessed directly, not via subdomain)
  const portainerUrl = order.serverIp ? `https://${order.serverIp}:9443` : null

  // Decrypt password if present
  let password: string | null = null
  if (order.portainerPasswordEnc) {
    try {
      password = credentialService.decrypt(order.portainerPasswordEnc)
    } catch (error) {
      console.error('Failed to decrypt Portainer password:', error)
    }
  }

  return NextResponse.json({
    url: portainerUrl,
    username: order.portainerUsername,
    password,
    syncedAt: order.credentialsSyncedAt,
    isConfigured: !!(order.portainerUsername && order.portainerPasswordEnc),
  })
}

/**
 * PATCH /api/v1/admin/orders/[id]/portainer
 * Update Portainer credentials (manual entry)
 */
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: orderId } = await context.params

  const order = await prisma.order.findUnique({
    where: { id: orderId },
    select: { id: true },
  })

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

  const body = await request.json()
  const { username, password } = body

  // Build update data
  const updateData: {
    portainerUsername?: string
    portainerPasswordEnc?: string
    credentialsSyncedAt?: Date
  } = {}

  if (username !== undefined) {
    updateData.portainerUsername = username
  }

  if (password !== undefined) {
    updateData.portainerPasswordEnc = credentialService.encrypt(password)
  }

  // Mark as manually entered (update sync timestamp)
  updateData.credentialsSyncedAt = new Date()

  await prisma.order.update({
    where: { id: orderId },
    data: updateData,
  })

  return NextResponse.json({ success: true })
}

/**
 * POST /api/v1/admin/orders/[id]/portainer
 * Test Portainer connection
 */
export async function POST(
  request: NextRequest,
  context: RouteContext
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: orderId } = await context.params

  try {
    const client = await createPortainerClient(orderId)

    if (!client) {
      return NextResponse.json({
        success: false,
        error: 'Portainer credentials not configured',
      })
    }

    const connected = await client.testConnection()

    return NextResponse.json({
      success: connected,
      error: connected ? null : 'Failed to connect to Portainer',
    })
  } catch (error) {
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : 'Connection test failed',
    })
  }
}
