import type { AxiosError } from 'axios'

import {
  JumpDestinationUnion,
  JumpJump,
  JumpJumpMethod
} from 'apiClient/services/devops/interface'

interface CancelErrorResponse {
  errcode?: string
  errmsg?: string
  message?: string
}

export function GetCancelError(error: unknown): {
  errcode: string
  errmsg: string
} {
  const axiosError = error as AxiosError<CancelErrorResponse>

  return {
    errcode:
      axiosError.response?.data?.errcode || axiosError.code || 'CANCEL_FAILED',
    errmsg:
      axiosError.response?.data?.errmsg ||
      axiosError.response?.data?.message ||
      axiosError.message ||
      'Normal cancellation failed'
  }
}

export function GetDestinationsFromUnion(
  union: JumpDestinationUnion | undefined
): string {
  if (union) {
    if (union.control_plane && union.control_plane.name) {
      return union.control_plane.name
    } else if (union.dedicated_cluster && union.dedicated_cluster.cluster_id) {
      return union.dedicated_cluster.cluster_id
    } else if (union.serverless_cluster && union.serverless_cluster.name) {
      return union.serverless_cluster.name
    } else if (union.byoc_cluster && union.byoc_cluster.bastion_name) {
      return union.byoc_cluster.bastion_name
    } else if (union.premium_cluster && union.premium_cluster.cluster_id) {
      return union.premium_cluster.cluster_id
    } else if (
      union.premium_resource_pool &&
      union.premium_resource_pool.resource_pool_id
    ) {
      return union.premium_resource_pool.resource_pool_id
    }
  }

  return 'unknown'
}

export function GetJumpCommand(jump: JumpJump | undefined): string {
  if (jump) {
    if (jump.method === JumpJumpMethod.k8s) {
      return `kubectl config use ${jump.attributes?.k8s?.context}`
    }
    if (jump.method === JumpJumpMethod.tailscale) {
      return `ssh ${jump.attributes?.tailscale?.user}@${jump.attributes?.tailscale?.dst_hostname}`
    }
  }

  return 'unknown'
}
