import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import {
  netcupService,
  NetcupAuthError,
  NetcupApiError,
} from '@/lib/services/netcup-service'

/**
 * GET /api/v1/admin/netcup/servers/[id]/snapshots
 * Get list of server snapshots
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

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

    const { id: serverId } = await params

    // Check if authenticated with Netcup
    const isAuth = await netcupService.isAuthenticated()
    if (!isAuth) {
      return NextResponse.json(
        { error: 'Not authenticated with Netcup' },
        { status: 401 }
      )
    }

    const snapshots = await netcupService.getSnapshots(serverId)

    return NextResponse.json({
      snapshots,
      count: snapshots.length,
    })
  } catch (error) {
    console.error('Error getting server snapshots:', error)

    if (error instanceof NetcupAuthError) {
      return NextResponse.json({ error: error.message }, { status: 401 })
    }

    if (error instanceof NetcupApiError) {
      return NextResponse.json(
        { error: error.message },
        { status: error.statusCode }
      )
    }

    return NextResponse.json(
      { error: 'Failed to get server snapshots' },
      { status: 500 }
    )
  }
}

/**
 * POST /api/v1/admin/netcup/servers/[id]/snapshots
 * Create a new snapshot or perform snapshot actions
 *
 * Body:
 * - action: 'create' | 'delete' | 'revert' | 'check'
 * - name?: string (snapshot name for create/delete/revert)
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

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

    const { id: serverId } = await params
    const body = await request.json()

    const { action, name } = body as {
      action: 'create' | 'delete' | 'revert' | 'check'
      name?: string
    }

    if (!action) {
      return NextResponse.json(
        { error: 'Action required' },
        { status: 400 }
      )
    }

    // Check if authenticated with Netcup
    const isAuth = await netcupService.isAuthenticated()
    if (!isAuth) {
      return NextResponse.json(
        { error: 'Not authenticated with Netcup' },
        { status: 401 }
      )
    }

    switch (action) {
      case 'check': {
        const result = await netcupService.canCreateSnapshot(serverId)
        return NextResponse.json(result)
      }

      case 'create': {
        const result = await netcupService.createSnapshot(serverId, name)
        return NextResponse.json({
          success: true,
          message: `Snapshot created: ${result.name}`,
          snapshot: result,
        })
      }

      case 'delete': {
        if (!name) {
          return NextResponse.json(
            { error: 'Snapshot name required for delete' },
            { status: 400 }
          )
        }

        await netcupService.deleteSnapshot(serverId, name)
        return NextResponse.json({
          success: true,
          message: `Snapshot deleted: ${name}`,
        })
      }

      case 'revert': {
        if (!name) {
          return NextResponse.json(
            { error: 'Snapshot name required for revert' },
            { status: 400 }
          )
        }

        const task = await netcupService.revertSnapshot(serverId, name)
        return NextResponse.json({
          success: true,
          message: `Reverting to snapshot: ${name}`,
          taskId: task.taskId,
        })
      }

      default:
        return NextResponse.json(
          { error: 'Invalid action. Use: create, delete, revert, or check' },
          { status: 400 }
        )
    }
  } catch (error) {
    console.error('Error performing snapshot action:', error)

    if (error instanceof NetcupAuthError) {
      return NextResponse.json({ error: error.message }, { status: 401 })
    }

    if (error instanceof NetcupApiError) {
      return NextResponse.json(
        { error: error.message },
        { status: error.statusCode }
      )
    }

    return NextResponse.json(
      { error: 'Failed to perform snapshot action' },
      { status: 500 }
    )
  }
}
