#!/usr/bin/env bash
# onx-cpanel-list-remote-accounts — Uzak WHM'deki tüm hesapları listele (whmapi1 listaccts).
#
# Input (stdin JSON): {host, port, login_user, auth_method:"password", password}
# Output (stdout JSON):
#   {accounts:[{username,domain,disk_used_mb,email,suspended}], total_disk_used_mb:N,
#    host:"...", whmapi_version:"1"}
#
# exit: 0=ok 1=bad input 2=preflight 3=bağlantı/komut hatası
# Deployed to: /usr/local/onoxsoft/bin/onx-cpanel-list-remote-accounts

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/_lib/common.sh"
source "${SCRIPT_DIR}/_lib/ssh-remote.sh"

require_root
onx_json_input
onx_ssh_remote_init

if [[ "${MOCK_MODE}" == "1" ]]; then
    jq -nc --arg host "$ONX_SSH_HOST" \
        '{accounts:[{username:"acme",domain:"acme.com",disk_used_mb:120,email:"a@acme.com",suspended:0}],
          total_disk_used_mb:120, host:$host, whmapi_version:"1"}'
    exit 0
fi

RAW=$(onx_ssh_run "whmapi1 --output=json listaccts 2>/dev/null")

# whmapi1 listaccts → .data.acct[]. diskused "MB" string olabilir ("123" / "1.2G");
# sadece tamsayı MB'yi çıkar (basit normalize).
ACCOUNTS=$(printf '%s' "$RAW" | jq -c '
    [ (.data.acct // [])[] | {
        username: (.user // ""),
        domain: (.domain // ""),
        disk_used_mb: (((.diskused // "0") | tostring | gsub("[^0-9]";"")) as $d | if $d == "" then 0 else ($d | tonumber) end),
        email: (.email // ""),
        suspended: (.suspended // 0)
    } | select(.username != "") ]' 2>/dev/null)

# whmapi1 yoksa/parse edilemezse açık hata.
if [[ -z "$ACCOUNTS" || "$ACCOUNTS" == "null" ]]; then
    onx_die 3 "whmapi1 listaccts çıktısı işlenemedi. WHM root erişimi + whmapi1 mevcut mu?"
fi

TOTAL_MB=$(printf '%s' "$ACCOUNTS" | jq '[.[].disk_used_mb] | add // 0')

jq -nc \
    --argjson accounts "$ACCOUNTS" \
    --argjson total "${TOTAL_MB:-0}" \
    --arg host "$ONX_SSH_HOST" \
    '{accounts:$accounts, total_disk_used_mb:$total, host:$host, whmapi_version:"1"}'
