# Image delete — remove Hetzner snapshot and clear local state file.

use ./state.nu *

export def image-delete [
    role: string
    --provider: string = "hetzner"
    --yes
] {
    let state = (image-state-read $provider $role)

    if $state.snapshot_id == "SNAPSHOT_PENDING" {
        print $"Role '($role)' has no snapshot to delete."
        return
    }

    if not $yes {
        print $"About to delete snapshot ($state.snapshot_id) for role '($provider)/($role)'"
        let answer = (input "Confirm? [y/N] ")
        if ($answer | str downcase | str trim) != "y" {
            print "Aborted."
            return
        }
    }

    let result = (^hcloud image delete $state.snapshot_id | complete)
    if $result.exit_code != 0 {
        error make { msg: $"hcloud image delete failed: ($result.stderr)" }
    }

    let path = (image-state-path $provider $role)
    if ($path | path exists) {
        rm $path
    }

    print $"Deleted snapshot ($state.snapshot_id) and removed state for '($provider)/($role)'."
}
