#!/usr/bin/env bash
# =====================================================================
# set-parent-ids.sh — link imported variations to their shop master article: writes the catalog's
# `shopItemId` into M_Product.ParentId (varchar 30, otherwise unused by the app) for every article of
# a merchant org, via the iDempiere REST API (the products/update route has no field for it).
#
#   ADMIN_USER=demo ORG_ID=1000018 WH_ID=1000018 CATALOG=/root/demo-setup/hess/catalog.json ./set-parent-ids.sh
#
# Env: REST [https://127.0.0.1:8443/api/v1], ADMIN_USER [demo], ADMIN_PASS [password: line of
# /root/demo-credentials.txt], CLIENT_ID/ROLE_ID [1000000], ORG_ID/WH_ID (merchant), CATALOG,
# KEY [shopItemId = catalog field holding the master id]. Idempotent: skips rows whose ParentId already
# matches. Needs curl + jq + psql access (reads the product list straight from Postgres).
# =====================================================================
set -euo pipefail; export LANG=C.UTF-8
REST="${REST:-https://127.0.0.1:8443/api/v1}"; ADMIN_USER="${ADMIN_USER:-demo}"
ADMIN_PASS="${ADMIN_PASS:-$(sed -n 's/^password: //p' /root/demo-credentials.txt | head -1)}"
CLIENT_ID="${CLIENT_ID:-1000000}"; ROLE_ID="${ROLE_ID:-1000000}"; ORG_ID="${ORG_ID:?}"; WH_ID="${WH_ID:?}"; CATALOG="${CATALOG:?}"; KEY="${KEY:-shopItemId}"
T="$(curl -sk -X POST "$REST/auth/tokens" -H 'Content-Type: application/json' -d "$(jq -n --arg u "$ADMIN_USER" --arg p "$ADMIN_PASS" --argjson c "$CLIENT_ID" --argjson r "$ROLE_ID" --argjson o "$ORG_ID" --argjson w "$WH_ID" \
  '{userName:$u,password:$p,parameters:{clientId:$c,roleId:$r,organizationId:$o,warehouseId:$w}}')" | jq -r .token)"
[ -n "$T" ] && [ "$T" != null ] || { echo "REST login failed" >&2; exit 1; }
MAP="$(mktemp)"; trap 'rm -f "$MAP"' EXIT
jq -r --arg k "$KEY" '.[] | select(.[$k] != null) | "\(.value)\t\(.[$k])"' "$CATALOG" > "$MAP"
n=0; ok=0; skip=0
while IFS='|' read -r pid value parent; do
  want="$(awk -F'\t' -v v="$value" '$1==v {print $2; exit}' "$MAP")"; [ -n "$want" ] || continue
  if [ "$parent" = "$want" ]; then skip=$((skip+1)); continue; fi
  n=$((n+1))
  res="$(curl -sk -X PUT "$REST/models/m_product/$pid" -H "Authorization: Bearer $T" -H 'Content-Type: application/json' -d "$(jq -n --arg p "$want" '{parentId:$p}')")"
  if echo "$res" | jq -e '.id' >/dev/null 2>&1; then ok=$((ok+1)); else echo "FAILED $value ($pid): $(echo "$res" | cut -c1-150)"; fi
  [ $((n % 200)) = 0 ] && echo "  $n updated"
done < <(sudo -u postgres psql -d idempiere -At -F'|' -c "select m_product_id, value, coalesce(parentid,'') from adempiere.m_product where ad_org_id=$ORG_ID order by 1" 2>/dev/null)
echo "DONE: parent ids set on $ok of $n articles ($skip already correct)"
