#!/usr/bin/env bash
set -euo pipefail

say(){ printf "\033[1;36m%s\033[0m\n" "$*"; }
err(){ printf "\033[1;31m%s\033[0m\n" "$*" >&2; }

say "▶ docker compose ps"
docker compose ps || { err "❌ Pas dans le bon dossier ?"; exit 1; }

say "▶ Test host → Nginx"
if curl -fsS http://localhost/api/health >/dev/null 2>&1; then
  say "✅ Host OK: http://localhost/api/health"
  exit 0
else
  err "⚠️ Host 502 (ou autre). On continue…"
fi

say "▶ API container up ?"
if ! docker compose ps | awk 'NR>1{print $1,$4}' | grep -q 'api .*Up'; then
  err "❌ Service api pas UP → démarrage…"
  docker compose up -d api
fi

say "▶ Test API inside api container"
docker compose exec api sh -lc 'apk add --no-cache curl >/dev/null 2>&1 || true; curl -i http://localhost:4000/api/health || true'

say "▶ Test depuis Nginx vers api:4000"
if docker compose exec web sh -lc 'wget -q -O- http://api:4000/api/health >/dev/null 2>&1'; then
  say "✅ Nginx atteint api:4000"
  TARGET="api:4000"
else
  err "⚠️ api:4000 KO. Test vers supersunday_api:4000…"
  if docker compose exec web sh -lc 'wget -q -O- http://supersunday_api:4000/api/health >/dev/null 2>&1'; then
    say "✅ Nginx atteint supersunday_api:4000"
    TARGET="supersunday_api:4000"
  else
    err "❌ Nginx n'atteint pas l'API par le réseau docker."
    say "Logs web (Nginx) :"; docker compose logs --since=2m web || true
    say "Logs api :"; docker compose logs --since=2m api || true
    exit 1
  fi
fi

say "▶ Vérifie/force nginx.conf → upstream ${TARGET}"
# Remplace le bloc upstream par la bonne cible
if [ -f nginx/nginx.conf ]; then
  # Portable sur macOS (BSD sed) : crée sauvegarde .bak
  sed -i '' -e "s#upstream api_upstream {[^}]*}#upstream api_upstream { server ${TARGET}; keepalive 16; }#g" nginx/nginx.conf
  docker compose restart web
else
  err "❌ nginx/nginx.conf introuvable"
  exit 1
fi

say "▶ Re-test host → Nginx"
curl -i http://localhost/api/health || { err "❌ Toujours KO"; exit 1; }
say "✅ OK via Nginx"