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

interface RouteContext {
  params: Promise<{ id: string; containerId: string; action: string }>
}

const ALLOWED_ACTIONS = ['start', 'stop', 'restart'] as const
type ContainerAction = (typeof ALLOWED_ACTIONS)[number]

/**
 * POST /api/v1/admin/orders/[id]/containers/[containerId]/[action]
 * Perform a container action (start, stop, restart)
 */
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, containerId, action } = await context.params

  // Validate action
  if (!ALLOWED_ACTIONS.includes(action as ContainerAction)) {
    return NextResponse.json(
      { error: `Invalid action: ${action}. Allowed actions: ${ALLOWED_ACTIONS.join(', ')}` },
      { status: 400 }
    )
  }

  try {
    const client = await createPortainerClient(orderId)

    if (!client) {
      return NextResponse.json(
        { error: 'Portainer credentials not configured for this order' },
        { status: 400 }
      )
    }

    // Execute the action
    switch (action as ContainerAction) {
      case 'start':
        await client.startContainer(containerId)
        break
      case 'stop':
        await client.stopContainer(containerId)
        break
      case 'restart':
        await client.restartContainer(containerId)
        break
    }

    return NextResponse.json({ success: true, action })
  } catch (error) {
    console.error(`Failed to ${action} container:`, error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : `Failed to ${action} container` },
      { status: 500 }
    )
  }
}
