#!/usr/bin/env bash
# =============================================================================
# onx-trash-list — Enumerate items inside ~/.trash/
#
# Purpose:
#   Returns soft-deleted items so the File Manager "Trash" view can render the
#   per-account recycle bin. Each entry corresponds to one .trash/<uuid>/
#   subdirectory and is restored from its .meta.json sidecar.
#
# Input (stdin JSON):
#   {
#     "username":  "onx_xxxx",
#     "max_age_days": null         -- optional; filter older entries when set
#   }
#
# Output (stdout JSON):
#   {
#     "username":     "onx_xxxx",
#     "trash_root":   "/home/onx_xxxx/.trash",
#     "count":        3,
#     "total_bytes":  12894,
#     "items": [
#       {
#         "trash_id":          "5f3a1b6e",
#         "original_path":     "public_html/old-stuff/draft.html",
#         "original_basename": "draft.html",
#         "size_bytes":        1247,
#         "is_dir":            false,
#         "deleted_at":        "2026-05-15T12:34:56Z",
#         "age_days":          0
#       },
#       ...
#     ]
#   }
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=execution-fail
# Deployed to: /usr/local/onoxsoft/bin/onx-trash-list
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=_lib/common.sh
source "${SCRIPT_DIR}/_lib/common.sh"

require_cmd jq
require_cmd find

onx_json_input

USERNAME="$(onx_json_field username)"
MAX_AGE_DAYS="$(onx_json_field max_age_days "")"

onx_validate_username "$USERNAME"

HOME_DIR="/home/${USERNAME}"
TRASH_ROOT="${HOME_DIR}/.trash"

# A missing trash dir is not an error — just empty result.
if [[ ! -d "${TRASH_ROOT}" ]]; then
    jq -nc \
        --arg username "${USERNAME}" \
        --arg trash_root "${TRASH_ROOT}" \
        '{username: $username, trash_root: $trash_root, count: 0, total_bytes: 0, items: []}'
    exit 0
fi

NOW_TS="$(date +%s)"
ITEMS_JSON="[]"
TOTAL_BYTES=0
COUNT=0

LINES=()

# Iterate /home/<user>/.trash/<uuid>/ directories.
shopt -s nullglob
for dir in "${TRASH_ROOT}"/*/; do
    [[ -d "${dir}" ]] || continue
    META="${dir%/}/.meta.json"
    [[ -f "${META}" ]] || continue

    # Read meta safely.
    if ! TRASH_ID="$(jq -r '.trash_id // empty' "${META}" 2>/dev/null)"; then
        continue
    fi
    [[ -z "${TRASH_ID}" ]] && continue

    ORIG_PATH="$(jq -r '.original_path // ""' "${META}" 2>/dev/null)"
    ORIG_BN="$(jq -r '.original_basename // ""' "${META}" 2>/dev/null)"
    SIZE="$(jq -r '.size_bytes // 0' "${META}" 2>/dev/null)"
    IS_DIR_RAW="$(jq -r '.is_dir // false' "${META}" 2>/dev/null)"
    DELETED_AT="$(jq -r '.deleted_at // ""' "${META}" 2>/dev/null)"

    # Age in days.
    DELETED_TS=0
    if [[ -n "${DELETED_AT}" ]]; then
        DELETED_TS="$(date -d "${DELETED_AT}" +%s 2>/dev/null || echo 0)"
    fi
    AGE_DAYS=0
    if (( DELETED_TS > 0 )); then
        AGE_DAYS=$(( (NOW_TS - DELETED_TS) / 86400 ))
    fi

    # Filter by max_age_days when set.
    if [[ -n "${MAX_AGE_DAYS}" && "${MAX_AGE_DAYS}" != "null" ]]; then
        if (( AGE_DAYS > MAX_AGE_DAYS )); then
            continue
        fi
    fi

    LINES+=("$(jq -nc \
        --arg trash_id "${TRASH_ID}" \
        --arg original_path "${ORIG_PATH}" \
        --arg original_basename "${ORIG_BN}" \
        --argjson size_bytes "${SIZE}" \
        --argjson is_dir "$([[ "${IS_DIR_RAW}" == "true" ]] && echo true || echo false)" \
        --arg deleted_at "${DELETED_AT}" \
        --argjson age_days "${AGE_DAYS}" \
        '{
            trash_id: $trash_id,
            original_path: $original_path,
            original_basename: $original_basename,
            size_bytes: $size_bytes,
            is_dir: $is_dir,
            deleted_at: $deleted_at,
            age_days: $age_days
         }')")

    TOTAL_BYTES=$(( TOTAL_BYTES + SIZE ))
    COUNT=$(( COUNT + 1 ))
done
shopt -u nullglob

if [[ ${#LINES[@]} -gt 0 ]]; then
    # Sort by deleted_at desc (newest first).
    ITEMS_JSON="$(printf '%s\n' "${LINES[@]}" | jq -s 'sort_by(.deleted_at) | reverse')"
fi

onx_log "trash-list: user=${USERNAME} count=${COUNT} bytes=${TOTAL_BYTES}"

jq -nc \
    --arg username "${USERNAME}" \
    --arg trash_root "${TRASH_ROOT}" \
    --argjson count "${COUNT}" \
    --argjson total_bytes "${TOTAL_BYTES}" \
    --argjson items "${ITEMS_JSON}" \
    '{
        username: $username,
        trash_root: $trash_root,
        count: $count,
        total_bytes: $total_bytes,
        items: $items
     }'
