#!/usr/bin/env bash
set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=shared/common.sh
source "$DIR/shared/common.sh"
_load_env

GLOBAL_ID="${SANDBOX_CONSIGNMENT_GLOBAL_ID:-${1:-}}"

if [ -z "$GLOBAL_ID" ]; then
  fail "Provide the consignment globalId via SANDBOX_CONSIGNMENT_GLOBAL_ID or as argument: $0 <globalId>"
fi

login

OUT_DIR="$DIR/downloads/$(echo "$GLOBAL_ID" | tr ':/' '__')"
mkdir -p "$OUT_DIR"

# GET a node endpoint (or absolute URL) — sets GET_STATUS and writes the body to $2.
#
# Blob hrefs come back built on the organisation's configured public origin, which
# is usually the web app rather than the node. That origin authenticates browser
# sessions by cookie, so the bearer token this script holds means nothing to it and
# the request is redirected to a login page. The node serves the same /blob path, so
# blob reads are addressed to the node the script is already authenticated against.
api_get() {
  local url="$1"
  local out_file="$2"
  case "$url" in
    http*://*/blob/*) url="${SUPPLY_CHAIN_NODE_URL}/blob/${url#*/blob/}" ;;
    http*) ;;
    *) url="${SUPPLY_CHAIN_NODE_URL}${url}" ;;
  esac
  GET_STATUS=$(curl -s -o "$out_file" -w "%{http_code}" \
    -H "Authorization: Bearer ${TOKEN}" \
    "$url" || true)
  GET_STATUS="${GET_STATUS:-000}"
}

echo "Reading as:     ${ORG_ID}"
echo "Consignment:    ${GLOBAL_ID}"
echo ""

# 1. The consignment itself — the dataspace read API.
CONSIGNMENTS_BASE="/supply-chain/data-space/consignments"
api_get "${CONSIGNMENTS_BASE}/${GLOBAL_ID}" "$OUT_DIR/consignment.json"
if [ "$GET_STATUS" != "200" ]; then
  fail "✗ Could not read consignment → HTTP ${GET_STATUS}: $(cat "$OUT_DIR/consignment.json" 2>/dev/null)"
fi
echo "✓ Consignment → downloads/$(basename "$OUT_DIR")/consignment.json"

# 2. The document attachments
api_get "${CONSIGNMENTS_BASE}/${GLOBAL_ID}/documents" "$OUT_DIR/documents.json"
if [ "$GET_STATUS" != "200" ]; then
  fail "✗ Could not list documents → HTTP ${GET_STATUS}: $(cat "$OUT_DIR/documents.json" 2>/dev/null)"
fi

doc_count=0
while IFS= read -r doc; do
  doc_id=$(echo "$doc" | jq -r '.documentId // "unknown"')
  doc_type=$(echo "$doc" | jq -r '.documentType // .documentCode // "unknown type"')
  revision=$(echo "$doc" | jq -r '.documentRevision // 0')
  extension=$(echo "$doc" | jq -r '.metadata.fileExtension // "bin"')
  href=$(echo "$doc" | jq -r '.href // empty')

  if [ -z "$href" ]; then
    echo "✗ ${doc_id} — no content href, skipping"
    continue
  fi

  doc_file="$OUT_DIR/${doc_id}-rev${revision}.${extension}"
  api_get "$href" "$doc_file"
  if [ "$GET_STATUS" = "200" ]; then
    echo "✓ ${doc_id} (${doc_type}, rev ${revision}) → downloads/$(basename "$OUT_DIR")/$(basename "$doc_file")"
    doc_count=$((doc_count + 1))
  else
    echo "✗ ${doc_id} — content download failed → HTTP ${GET_STATUS}"
    rm -f "$doc_file"
  fi
done < <(jq -c '.entities[]?' "$OUT_DIR/documents.json")

echo ""
echo "Done — ${doc_count} document(s) downloaded to downloads/$(basename "$OUT_DIR")/"
