#!/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

DATA_FILE="$DIR/../data/consignment-lifecycle.template.ndjson"
DELAY="${SANDBOX_ACTIVITY_DELAY:-120}"

_load_route

# A fresh reference per run, so each run publishes a new consignment instead of
# revising the previous one. Set SANDBOX_CONSIGNMENT_REFERENCE to reuse a past
# reference and publish a new revision of that consignment instead.
# Note: SANDBOX_CONSIGNMENT_GLOBAL_ID is not read here — it selects which
# consignment fetch-consignment.sh and send-match.sh act on.
REFERENCE="${SANDBOX_CONSIGNMENT_REFERENCE:-$(date -u +%Y%m%d-%H%M%S)}"
CONSIGNMENT_ID="${SANDBOX_CONSIGNMENT_PREFIX:-TESTFF}-${REFERENCE}"
CONSIGNMENT_GLOBAL_ID="${SANDBOX_GLOBAL_ID_PREFIX:-6-GB-GB000000000001}-${REFERENCE}"
CARRIER_NAME="${SANDBOX_CARRIER_NAME:-TestCarrier}"
CARRIER_ID="${SANDBOX_CARRIER_ID:-TESTCARRIER001}"

[ -f "$DATA_FILE" ] || fail "Data file not found: $DATA_FILE"

# Every {{PLACEHOLDER}} in the template file resolves through this table.
TEMPLATE_VALUES=$(jq -nc \
  --arg exitName "$PORT_OF_EXIT_NAME" \
  --arg exitCode "$PORT_OF_EXIT_CODE" \
  --arg entryName "$PORT_OF_ENTRY_NAME" \
  --arg entryCode "$PORT_OF_ENTRY_CODE" \
  --arg consignmentId "$CONSIGNMENT_ID" \
  --arg consignmentGlobalId "$CONSIGNMENT_GLOBAL_ID" \
  --arg carrierName "$CARRIER_NAME" \
  --arg carrierId "$CARRIER_ID" \
  '{
    "{{PORT_OF_EXIT_NAME}}": $exitName,
    "{{PORT_OF_EXIT_CODE}}": $exitCode,
    "{{PORT_OF_ENTRY_NAME}}": $entryName,
    "{{PORT_OF_ENTRY_CODE}}": $entryCode,
    "{{CONSIGNMENT_ID}}": $consignmentId,
    "{{CONSIGNMENT_GLOBAL_ID}}": $consignmentGlobalId,
    "{{CARRIER_NAME}}": $carrierName,
    "{{CARRIER_ID}}": $carrierId
  }')

login

total=$(grep -c . "$DATA_FILE" || true)

echo "Publishing as:  ${ORG_ID}"
echo "Consignment:    ${CONSIGNMENT_ID}"
echo "Global ID:      ${CONSIGNMENT_GLOBAL_ID}"
echo "Route:          ${PORT_OF_EXIT_NAME} (${PORT_OF_EXIT_CODE}) → ${PORT_OF_ENTRY_NAME} (${PORT_OF_ENTRY_CODE})"
echo "Activities:     ${total} — delay between activities: ${DELAY}s"
echo ""

index=0
while IFS= read -r line; do
  [ -z "$line" ] && continue

  # Placeholders also appear inside longer strings (document identifiers, URLs),
  # so substitute on substrings rather than only on whole values.
  activity=$(echo "$line" | jq -c --arg org "$ORG_ID" --argjson values "$TEMPLATE_VALUES" \
    'walk(
       if type == "string"
       then reduce ($values | to_entries[]) as $entry (.; split($entry.key) | join($entry.value))
       else . end
     ) | .generator = $org')
  type=$(echo "$activity" | jq -r '.type')
  name=$(echo "$activity" | jq -r '.name // .type')
  # Events are identified by their type code, everything else by its identifier.
  object_id=$(echo "$activity" | jq -r '.object.typeCode // .object.identifier // .object.type // "?"')

  index=$((index + 1))

  if [ "$index" -gt 1 ]; then
    echo "  waiting ${DELAY}s..."
    sleep "$DELAY"
  fi

  notify_inbox "$activity"

  if inbox_ok; then
    echo "[${index}/${total}] ✓ ${type} ${name} — ${object_id}"
  else
    fail "[${index}/${total}] ✗ ${type} ${name} — ${object_id} → HTTP ${INBOX_STATUS}: ${INBOX_RESPONSE}"
  fi
done < "$DATA_FILE"

echo ""
echo "Done — ${index} activities published"
echo "Consignment globalId:"
echo "  ${CONSIGNMENT_GLOBAL_ID}"
