
use ../lib_provisioning/config/accessor.nu *
use ../../../extensions/providers/hetzner/nulib/hetzner/api.nu *

def prompt_delete [
  target: string
  target_name: string
  yes: bool
  name?: string
] {
  match $name {
    "h" | "help" => {
      ^((get-provisioning-name)) "-mod" $target "--help"
      exit 0
    }
  }
  if not $yes or not ((($env.PROVISIONING_ARGS? | default "")) | str contains "--yes")  {
    _print ( $"To (_ansi red_bold)delete ($target_name) (_ansi reset) " +
      $" (_ansi green_bold)($name)(_ansi reset) type (_ansi green_bold)yes(_ansi reset) ? "
    )
    let user_input = (input --numchar 3)
    if $user_input != "yes" and $user_input != "YES"  {
      exit 1
    }
    $name
  } else {
    $env.PROVISIONING_ARGS = ($env.PROVISIONING_ARGS? | find -v "yes")
    ($name | default "" | str replace "yes" "")
  }
}

# Delete infrastructure and services
export def "main delete" [
  target?: string     # server (s) | task (t) | service (sv)
  name?: string       # target name in settings
  ...args                 # Args for create command
  --serverpos (-p): int   # Server position in settings
  --keepstorage           # Keep storage
  --yes (-y)              # confirm delete
  --wait (-w)             # Wait servers to be created
  --infra (-i): string    # Infra path
  --settings (-s): string # Settings path
  --outfile (-o): string  # Output file
  --debug (-x)            # Use Debug mode
  --xm             # Debug with PROVISIONING_METADATA
  --xc             # Debuc for task and services locally PROVISIONING_DEBUG_CHECK
  --xr             # Debug for remote servers PROVISIONING_DEBUG_REMOTE
  --xld            # Log level with DEBUG PROVISIONING_LOG_LEVEL=debug
  --metadata       # Error with metadata (-xm)
  --notitles       # not tittles
  --out: string    # Print Output format: json, yaml, text (default)
] {
  if ($out | is-not-empty) {
    $env.PROVISIONING_OUT = $out
    $env.PROVISIONING_NO_TERMINAL = true
  }
  parse_help_command "delete" --end
  if $debug { $env.PROVISIONING_DEBUG = true }
  let use_debug = if $debug or (is-debug-enabled) { "-x" } else { "" }
  match $target {
    "server"| "servers" | "s" => {
      prompt_delete "server" "servers" $yes $name
      ^$"((get-provisioning-name))" $use_debug -mod "server" ($env.PROVISIONING_ARGS | str replace $target '') --yes --notitles
    },
    "storage" => {
      prompt_delete "server" "storage" $yes $name
      ^$"((get-provisioning-name))" $use_debug -mod "server" $env.PROVISIONING_ARGS --yes --notitles
    },
    "taskserv" | "taskservs" | "t" => {
      prompt_delete "taskserv" "tasks/services" $yes $name
      ^$"((get-provisioning-name))" $use_debug -mod "tasksrv" ($env.PROVISIONING_ARGS | str replace $target '') --yes --notitles
    },
    "clusters"| "clusters" | "cl" => {
      prompt_delete "cluster" "cluster" $yes $name
      ^$"((get-provisioning-name))" $use_debug -mod "cluster" ($env.PROVISIONING_ARGS | str replace $target '') --yes --notitles
    },
    "fip" | "floating-ip" => {
      let fip_name = ($name | default "")
      if ($fip_name | is-empty) {
        error make { msg: "floating IP name required — usage: provisioning delete fip <name>" }
      }
      prompt_delete "floating-ip" "floating IP" $yes $fip_name

      let fips = (hetzner_api_list_floating_ips)
      let matches = ($fips | where {|f| $f.name == $fip_name })
      if ($matches | is-empty) {
        error make { msg: $"Floating IP '($fip_name)' not found in Hetzner" }
      }
      let fip = ($matches | first)
      let fip_id = ($fip.id | into string)

      let assigned = ($fip | get -o server | default null)
      if $assigned != null {
        print $"  unassigning ($fip_name) from server ($assigned) ..."
        let _a = (hetzner_api_unassign_floating_ip $fip_id)
      }

      print $"  deleting floating IP ($fip_name) [($fip_id)] ..."
      hetzner_api_delete_floating_ip $fip_id
      print $"  ✓ ($fip_name) deleted"
    },
     _ => {
        invalid_task "delete" ($target | default "") --end
        exit
    },
  }
}
