#!/usr/bin/env bash
# scripts/smoke-phase5.sh — smoke for stats + export endpoints.
# Run from lima-city SSH with a live session cookie in SID.
#   SID=<sid-value> bash scripts/smoke-phase5.sh
# Pre-flight seeds today + today-7d weight + one meal today so
# summary's delta_7d has two anchors to compute against.

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)
SEVEN=$(date -u -d '7 days ago' +%F)

req() { # $1=method $2=path $3=body(or "") $4=expected-status → BODY / HDRS
  BODY=$(mktemp); HDRS=$(mktemp)
  local args=(-sS -o "$BODY" -D "$HDRS" -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 body missing: $1";   cat "$BODY"; exit 1; }; }
has_hdr() { grep -qiE "$1" "$HDRS" || { echo "FAIL header missing: $1"; cat "$HDRS"; exit 1; }; }

echo "── seed"
req POST /api/meals.php  "{\"logged_date\":\"$TODAY\",\"logged_at\":\"$NOW\",\"name\":\"Seed\",\"kcal\":500}" 201
req POST /api/weight.php "{\"measured_date\":\"$TODAY\",\"measured_at\":\"$NOW\",\"kg\":72.5}" 200
req POST /api/weight.php "{\"measured_date\":\"$SEVEN\",\"measured_at\":\"${SEVEN}T12:00:00Z\",\"kg\":73.0}" 200

echo "── summary"
req GET "/api/stats/summary.php?today=$TODAY"       "" 200; has '"today_kcal":'; has '"goal_kcal":'
req GET "/api/stats/summary.php"                    "" 400; has '"error":"missing_field"'
req GET "/api/stats/summary.php?today=not-a-date"   "" 400; has '"error":"invalid_field"'

echo "── weight-series"
req GET "/api/stats/weight-series.php?range=7d"     "" 200; has '"points":\['
req GET "/api/stats/weight-series.php?range=all"    "" 200; has '"points"'
req GET "/api/stats/weight-series.php?range=42d"    "" 400; has '"error":"invalid_field"'
req GET "/api/stats/weight-series.php"              "" 400; has '"error":"invalid_field"'

echo "── export"
req GET /api/export.php "" 200
has '"exported_at":'; has '"meals":\['; has '"weight_entries":\['; has '"settings"'
has_hdr '^content-disposition:.*attachment;.*filename="kcal-export-[0-9]{4}-[0-9]{2}-[0-9]{2}\.json"'
req GET "/api/export.php?format=csv" "" 400; has '"error":"invalid_field"'

echo "── ALL GREEN"
