#!/bin/bash

# Instance Commands Handler
# Multi-instance lifecycle for multi-instance-capable apps. Mutating verbs route
# through the task system (mirroring `app install`): the WebUI queues a task, the
# processor re-invokes the CLI with LIBREPORTAL_TASK_EXEC=1, and only then does
# the real work run. No new mutating backend API endpoint is introduced.

cliHandleInstanceCommands()
{
    local action="$initial_command2"
    local type="$initial_command3"
    local name="$initial_command4"
    local domain_idx="$initial_command5"
    local subdomain="$initial_command6"

    case "$action" in
        "create")
            if [[ -z "$type" || -z "$name" ]]; then
                isNotice "Usage: libreportal instance create <type> <name> [domain_index] [subdomain]"
                cliShowInstanceHelp
                return 1
            fi
            if [[ "$LIBREPORTAL_TASK_EXEC" == "1" ]]; then
                instanceCreate "$type" "$name" "$domain_idx" "$subdomain"
            else
                local _cmd="libreportal instance create $type $name"
                [[ -n "$domain_idx" ]] && _cmd+=" $domain_idx"
                [[ -n "$subdomain" ]]  && _cmd+=" $subdomain"
                cliTaskRun "$_cmd" "install" "${type}_$(instanceIdPart "$name")"
            fi
            ;;

        "remove"|"delete")
            # Here $type holds the instance slug (positional reuse).
            local slug="$type"
            if [[ -z "$slug" ]]; then
                isNotice "Usage: libreportal instance remove <slug>"
                return 1
            fi
            if [[ "$LIBREPORTAL_TASK_EXEC" == "1" ]]; then
                instanceRemove "$slug"
            else
                cliTaskRun "libreportal instance remove $slug" "uninstall" "$slug"
            fi
            ;;

        "list")
            instanceList "$type"   # $type optional = filter by app type
            ;;

        *)
            cliShowInstanceHelp
            ;;
    esac
}
