#!/bin/bash
# Confirm the incoming-invoice PDF attach works end-to-end (Eingangsrechnungen).
# Mirrors exactly what server/utils/inbox/strapiAttach.ts does:
#   1) create an ad-attachment record (POST $STRAPIV1/ad-attachments)
#   2) upload + LINK the file (POST $STRAPIUPLOAD/api/upload with field/ref/refId)
#   3) verify the file is linked on the ad-attachment
# curl builds a correct multipart body, so a 201 here = the endpoint+flow are good.
# Run ON the prod server:
#   bash reference/test-scripts/test-strapi-upload.sh [/path/to/real.pdf]
#   ENV_FILE=/some/.env REC_ID=123456 bash reference/test-scripts/test-strapi-upload.sh
set -uo pipefail

ENV_FILE="${ENV_FILE:-/opt/erp-nuxt-frontend/.env}"
[ -f "$ENV_FILE" ] || ENV_FILE=".env"
getenv() { grep -E "^$1=" "$ENV_FILE" | head -1 | cut -d= -f2- | tr -d "\"' "; }

TOKEN=$(getenv STRAPITOKEN)
STRAPIV1=$(getenv STRAPIV1)            # config.api.strapi — where ad-attachments live (…/media-api)
STRAPIUPLOAD=$(getenv STRAPIUPLOAD)    # /api/upload base (e.g. http://127.0.0.1:1337)
: "${STRAPIUPLOAD:=http://127.0.0.1:1337}"

echo "env=$ENV_FILE  STRAPITOKEN_len=${#TOKEN}"
echo "STRAPIV1=$STRAPIV1"
echo "STRAPIUPLOAD=$STRAPIUPLOAD"

PDF="${1:-/tmp/test.pdf}"
if [ ! -f "$PDF" ]; then
  printf '%%PDF-1.4\n1 0 obj<</Type/Catalog>>endobj\ntrailer<</Root 1 0 R>>\n%%%%EOF' > /tmp/test.pdf
  PDF=/tmp/test.pdf
fi
echo "pdf=$PDF ($(wc -c < "$PDF") bytes)"

TABLE_ID=318                       # C_Invoice
REC_ID="${REC_ID:-999999}"         # dummy Record_ID for the test
echo "AD_Table_ID=$TABLE_ID  Record_ID=$REC_ID"

echo ""; echo "=== STEP 1: create ad-attachment record (POST \$STRAPIV1/ad-attachments) ==="
ATT=$(curl -sSk -w $'\nHTTP %{http_code}' -X POST "$STRAPIV1/ad-attachments" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d "{\"data\":{\"AD_Table_ID\":$TABLE_ID,\"Record_ID\":$REC_ID}}")
echo "$ATT"
STRAPI_ID=$(printf '%s' "$ATT" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
echo "-> ad-attachment id = ${STRAPI_ID:-<none>}"

echo ""; echo "=== STEP 2: upload + LINK to that record (POST \$STRAPIUPLOAD/api/upload) ==="
curl -sSk -w $'\nHTTP %{http_code}\n' -X POST "$STRAPIUPLOAD/api/upload" \
  -H "Authorization: Bearer $TOKEN" \
  -F "field=attachment" \
  -F "ref=api::ad-attachment.ad-attachment" \
  -F "refId=${STRAPI_ID:-0}" \
  -F "fileInfo={\"caption\":\"$REC_ID\",\"alternativeText\":\"test.pdf\"}" \
  -F "files=@$PDF;type=application/pdf"

echo ""; echo "=== STEP 3: verify the file is linked on the ad-attachment ==="
# -g/--globoff: the URL contains [ ] which curl otherwise treats as a glob range.
curl -gsSk -w $'\nHTTP %{http_code}\n' \
  "$STRAPIV1/ad-attachments?filters[Record_ID][\$eq]=$REC_ID&populate=*" \
  -H "Authorization: Bearer $TOKEN"

echo ""
echo "VERDICT: STEP 2 = HTTP 201 and STEP 3 shows the file under \"attachment\" => the app flow works."
