#!/usr/bin/env bash
# scripts/smoke-phase4.sh — thin smoke for meals / weight / settings.
# Run from lima-city SSH after the three .php files are uploaded.
#   SID=<sid-cookie-value> bash scripts/smoke-phase4.sh
# Green = every line OK. First red halts and dumps the response body.

set -eu
BASE="https://kcal.yairatala.de"
: "${SID:?SID env var required (paste the sid cookie value)}"
H=(-H "Cookie: sid=$SID" -H "Content-Type: application/json")
TODAY=$(date -u +%F); NOW=$(date -u +%FT%TZ)

req() { # $1=method $2=path $3=body(or "") $4=expected-status → BODY=tmpfile
  BODY=$(mktemp)
  local args=(-sS -o "$BODY" -w '%{http_code}' -X "$1" "${H[@]}")
  [[ -n "$3" ]] && args+=(--data "$3")
  ST=$(curl "${args[@]}" "$BASE$2")
  [[ "$ST" == "$4" ]] || { echo "FAIL $1 $2: want $4 got $ST"; cat "$BODY"; exit 1; }
  echo "OK   $1 $2 → $ST"
}
has() { grep -qE "$1" "$BODY" || { echo "FAIL no match: $1"; cat "$BODY"; exit 1; }; }

echo "── meals"
req POST /api/meals.php "{\"logged_date\":\"$TODAY\",\"logged_at\":\"$NOW\",\"name\":\"Smoke\",\"kcal\":300}" 201
MID=$(grep -oE '"id":[0-9]+' "$BODY" | head -1 | cut -d: -f2); echo "     mid=$MID"
req POST /api/meals.php "{\"logged_date\":\"$TODAY\",\"logged_at\":\"$NOW\",\"name\":\"Bad\",\"kcal\":150.5}" 400
req GET "/api/meals.php?from=$TODAY&to=$TODAY" "" 200; has "\"id\":$MID[^0-9]"
req DELETE /api/meals.php "{\"id\":$MID}" 200

echo "── weight"
req POST /api/weight.php "{\"measured_date\":\"$TODAY\",\"measured_at\":\"$NOW\",\"kg\":72.5}" 200
WID=$(grep -oE '"id":[0-9]+' "$BODY" | head -1 | cut -d: -f2); echo "     wid=$WID"
req POST /api/weight.php "{\"measured_date\":\"$TODAY\",\"measured_at\":\"$NOW\",\"kg\":73.0}" 200
WID2=$(grep -oE '"id":[0-9]+' "$BODY" | head -1 | cut -d: -f2)
[[ "$WID" == "$WID2" ]] || { echo "FAIL upsert id drift: $WID → $WID2"; cat "$BODY"; exit 1; }
has '"kg":73(\.0+)?,'; echo "OK   upsert same id, kg→73"
req POST /api/weight.php "{\"measured_date\":\"$TODAY\",\"measured_at\":\"$NOW\",\"kg\":600}" 400
req DELETE /api/weight.php "{\"id\":$WID}" 200

echo "── settings"
req GET /api/settings.php "" 200; has '"daily_kcal_goal":2200,'; has '"unit_weight":"kg"'
req PATCH /api/settings.php '{"daily_kcal_goal":2400}' 200; has '"daily_kcal_goal":2400,'
req PATCH /api/settings.php '{"unit_weight":"KG"}' 400
req GET /api/settings.php "" 200; has '"daily_kcal_goal":2400,'

echo "── ALL GREEN"
