#!/usr/bin/env bash

# ============================================
# Lifecycle
# ============================================

function cmd::remove::on_load() {
  flag::register --name
  flag::register --type
  flag::register --force
}

# ============================================
# Help
# ============================================

function cmd::remove::help() {
  cat <<EOF
Usage: wgctl remove --name <name> [options]

Permanently remove a WireGuard client.
This will delete the client config, keys, and remove it from the server.

Options:
  --name <name>   Full client name (e.g. phone-nuno)
  --force         Skip confirmation prompt

Examples:
  wgctl remove --name phone-nuno
  wgctl rm --name phone-nuno --force
EOF
}

# ============================================
# Run
# ============================================

function cmd::remove::run() {
  local name="" type="" force=false

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --name)  name="$2";         shift 2 ;;
      --type)  type="$2";         shift 2 ;;
      --force) force=true;        shift   ;;
      --help)  cmd::remove::help; return  ;;
      *)
        log::error "Unknown flag: $1"
        cmd::remove::help
        return 1
        ;;
    esac
  done

  if [[ -z "$name" ]]; then
    log::error "Missing required flag: --name"
    cmd::remove::help
    return 1
  fi

  name=$(peers::resolve_and_require "$name" "$type") || return 1

  if ! $force; then
    read -r -p "Are you sure you want to permanently remove '${name}'? [y/N] " confirm
    case "$confirm" in
      [yY][eE][sS]|[yY]) ;;
      *)
        log::info "Aborted"
        return 0
        ;;
    esac
  fi

  log::section "Removing client: ${name}"

  local client_ip was_blocked=false
  client_ip=$(peers::get_ip "$name")
  peers::is_blocked "$name" && was_blocked=true

  peers::purge "$name" "$client_ip" "$was_blocked" || return 1

  # Detach from identity after successful removal
  identity::auto_detach "$name"

  log::wg_success "Client removed: ${name}"
}

# _cleanup kept as a shim — callers should prefer peers::purge directly
function cmd::remove::_cleanup() {
  local name="${1:-}" client_ip="${2:-}" was_blocked="${3:-false}"
  peers::purge "$name" "$client_ip" "$was_blocked"
}