#!/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; }

test -f docker-compose.yml || { err "❌ docker-compose.yml introuvable ici"; exit 1; }

say "🧹 down --remove-orphans…"
docker compose down --remove-orphans || true

say "🏗 build --no-cache…"
docker compose build --no-cache

say "🚀 up -d (db, api, web)…"
docker compose up -d

say "🔎 ps:"
docker compose ps

say "⏳ test santé API via Nginx: http://localhost/api/health (60s max)"
deadline=$(( $(date +%s) + 60 ))
ok=false
while [[ $(date +%s) -lt $deadline ]]; do
  if curl -fsS http://localhost/api/health >/dev/null 2>&1; then ok=true; break; fi
  sleep 2
done
[[ "$ok" == "true" ]] || { err "❌ API pas encore OK. Logs:"; docker compose logs --tail=80 api || true; exit 1; }

say "✅ OK: Frontend http://localhost  |  API via proxy http://localhost/api/…"
