#!/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:-}}"
IDENTIFIER="${SANDBOX_CONSIGNMENT_IDENTIFIER:-${2:-}}"

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

login

# The match payload names the consignment by both its globalId and its identifier.
# The identifier is looked up from the consignment when it wasn't supplied, but
# sending a match is a write and must not depend on being able to read: the
# notification that prompts it already carries the consignment's details, and a
# location operator whose read access is still being set up can pass the
# identifier directly rather than being blocked.
if [ -z "$IDENTIFIER" ]; then
  consignment=$(curl -s "${SUPPLY_CHAIN_NODE_URL}/supply-chain/data-space/consignments/${GLOBAL_ID}" \
    -H "Authorization: Bearer ${TOKEN}" || true)
  IDENTIFIER=$(echo "$consignment" | jq -r '.identifier // empty' 2>/dev/null || true)
fi

if [ -z "$IDENTIFIER" ]; then
  fail "Could not read consignment ${GLOBAL_ID} to resolve its identifier, and none was given.
Pass it as the second argument or as SANDBOX_CONSIGNMENT_IDENTIFIER:
  $0 ${GLOBAL_ID} <identifier>
Response was: ${consignment}"
fi

now=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

echo "Sending as:     ${ORG_ID}"
echo "Consignment:    ${IDENTIFIER} (${GLOBAL_ID})"
echo "Event:          twin:locationOperatorMatch at ${now}"
echo ""

# The journey event: it lands in the consignment's `events` list and advances
# the consignment's status.
match_event=$(cat <<EOF
{
  "@context": [
    "https://www.w3.org/ns/activitystreams",
    "https://vocabulary.uncefact.org/unece-context-D23B.jsonld"
  ],
  "type": "Add",
  "name": "Event",
  "generator": "${ORG_ID}",
  "actor": {
    "@context": "https://vocabulary.uncefact.org/unece-context-D23B.jsonld",
    "type": "TradeParty",
    "registeredId": {
      "@type": "https://ref.gs1.org/voc/OrganizationID_Type-DID",
      "@value": "${ORG_ID}"
    }
  },
  "object": {
    "@context": "https://vocabulary.uncefact.org/unece-context-D23B.jsonld",
    "type": "SupplyChainEvent",
    "typeCode": "twin:locationOperatorMatch",
    "occurrenceDateTime": "${now}"
  },
  "target": {
    "@context": "https://vocabulary.uncefact.org/unece-context-D23B.jsonld",
    "type": "Consignment",
    "globalId": "${GLOBAL_ID}",
    "identifier": "${IDENTIFIER}"
  },
  "updated": "${now}"
}
EOF
)

notify_inbox "$match_event"

if inbox_ok; then
  echo "✓ twin:locationOperatorMatch sent for consignment ${GLOBAL_ID}"
else
  fail "✗ twin:locationOperatorMatch failed → HTTP ${INBOX_STATUS}: ${INBOX_RESPONSE}"
fi
