#!/usr/bin/env bash
#
# sync-postman.sh — refresh the API SOT chain after the live api/bo specs change.
#
# Pipeline:
#   1. snapshot the previous OpenAPI JSON (so we can diff)
#   2. re-pull live OpenAPI from the running ebit-api stack
#   3. regenerate Postman collections via openapi-to-postmanv2
#   4. emit a JSON diff under docs/api/changelog-draft-<date>.diff
#   5. print a manual review checklist
#
# Pre-requisites:
#   - ebit-api running locally (api on :4000, bo on :4003). See ebit-api README.
#   - node + npm available for openapi-to-postmanv2 (auto-installed under /tmp/postman-conv).
#   - python3 available (used by docs/api-reference/_gen.py).
#
# Usage:
#   ./docs/api/sync-postman.sh        # from repo root (/home/ubuntu/ebit)
#   ./docs/api/sync-postman.sh --skip-pull   # use the existing JSON, just regen collections
#
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$REPO_ROOT"

OPENAPI_DIR="$REPO_ROOT/docs/api-reference/openapi"
POSTMAN_DIR="$REPO_ROOT/docs/api/postman"
CONV_DIR="/tmp/postman-conv"
DATE_TAG="$(date +%Y%m%d)"

API_URL="${API_URL:-http://localhost:4000/swagger.json}"
BO_URL="${BO_URL:-http://localhost:4003/swagger.json}"

SKIP_PULL=0
for arg in "$@"; do
  case "$arg" in
    --skip-pull) SKIP_PULL=1 ;;
    -h|--help) sed -n '1,30p' "$0"; exit 0 ;;
  esac
done

echo "==> [1/5] snapshotting previous OpenAPI JSON"
for f in "$OPENAPI_DIR/api.openapi.json" "$OPENAPI_DIR/bo.openapi.json"; do
  if [[ -f "$f" ]]; then
    cp -f "$f" "$f.prev"
  else
    echo "    (no $f yet — first run, no .prev snapshot)"
  fi
done

if [[ "$SKIP_PULL" -eq 0 ]]; then
  echo "==> [2/5] pulling live OpenAPI"
  curl -fsS "$API_URL" -o "$OPENAPI_DIR/api.openapi.json"
  curl -fsS "$BO_URL"  -o "$OPENAPI_DIR/bo.openapi.json"
else
  echo "==> [2/5] --skip-pull — using existing OpenAPI JSON"
fi

echo "==> [3/5] regenerating Postman collections"
if [[ ! -d "$CONV_DIR/node_modules/openapi-to-postmanv2" ]]; then
  echo "    bootstrapping openapi-to-postmanv2 in $CONV_DIR"
  mkdir -p "$CONV_DIR"
  ( cd "$CONV_DIR" && npm init -y >/dev/null && npm i openapi-to-postmanv2@5 >/dev/null )
fi

# Reuse the convert.js shipped alongside this script if present, otherwise use /tmp copy.
CONVERT_JS="$REPO_ROOT/docs/api/_convert-openapi-to-postman.js"
if [[ ! -f "$CONVERT_JS" ]]; then
  CONVERT_JS="$CONV_DIR/convert.js"
fi

node "$CONVERT_JS" \
  "$OPENAPI_DIR/api.openapi.json" \
  "$POSTMAN_DIR/ebit-api.postman_collection.json" \
  "ebit api (port 4000)" \
  || { echo "FAIL: api conversion"; exit 1; }

node "$CONVERT_JS" \
  "$OPENAPI_DIR/bo.openapi.json" \
  "$POSTMAN_DIR/ebit-bo.postman_collection.json" \
  "ebit bo (port 4003)" \
  || { echo "FAIL: bo conversion"; exit 1; }

# Validate JSON parseability — Postman silently rejects malformed collections.
python3 -c "
import json, sys
for f in sys.argv[1:]:
    json.load(open(f))
    print('  OK', f)
" "$POSTMAN_DIR/ebit-api.postman_collection.json" \
  "$POSTMAN_DIR/ebit-bo.postman_collection.json"

echo "==> [4/5] writing changelog-draft-$DATE_TAG.diff"
DRAFT="$REPO_ROOT/docs/api/changelog-draft-$DATE_TAG.diff"
{
  for app in api bo; do
    echo "########## $app.openapi.json ##########"
    if [[ -f "$OPENAPI_DIR/$app.openapi.json.prev" ]]; then
      diff -u "$OPENAPI_DIR/$app.openapi.json.prev" "$OPENAPI_DIR/$app.openapi.json" || true
    else
      echo "(no previous snapshot — full content captured at v1.0.0 baseline)"
    fi
    echo
  done
} > "$DRAFT"
echo "    wrote $DRAFT"

# Endpoint summary side-by-side (helps the human spot added/removed paths fast).
echo "==> [5/5] endpoint summary"
python3 "$REPO_ROOT/docs/api/_extract-endpoints.py" \
  "$OPENAPI_DIR/api.openapi.json" \
  "$OPENAPI_DIR/bo.openapi.json"

cat <<EOF

----------------------------------------------------------------------
Refresh complete. Manual follow-up:

  1. Inspect $DRAFT — categorise each change as breaking / additive / deprecation.
  2. Re-render docs/api-reference/api.md + bo.md:
        python3 docs/api-reference/_gen.py
  3. Append a new section to docs/api/changelog.md (use the "Forward template").
  4. Bump info.version in the Nest buildSwagger call (see apps/api/src/main.ts and apps/bo/src/main.ts).
  5. Commit all four artefacts together: openapi/*.json + postman/*.json + api.md + changelog.md.

See docs/api/sync-changelog.md for the full curation guide.
----------------------------------------------------------------------
EOF
