#!/usr/bin/env bash
# Smoke VM123 Finance + Ops Console — semáforo FINANCE_RELEASE=GREEN/RED
# Uso: ./smoke-vm123.sh

set -euo pipefail

LAN="${VM123_LAN:-http://10.10.10.123}"
FAIL=0
pass() { echo "  OK  $1"; }
fail() { echo "  FAIL $1"; FAIL=$((FAIL + 1)); }

check_code() {
  local name="$1" url="$2" expect="${3:-200}"
  local code
  code=$(curl -sk -o /dev/null -w "%{http_code}" --connect-timeout 15 "$url" 2>/dev/null || echo "000")
  if [[ "$expect" == *"|"* ]]; then
    IFS='|' read -ra codes <<< "$expect"
    for c in "${codes[@]}"; do
      [[ "$code" == "$c" ]] && { pass "$name ($code)"; return; }
    done
    fail "$name ($code, esperado $expect)"
  else
    [[ "$code" == "$expect" ]] && pass "$name ($code)" || fail "$name ($code, esperado $expect)"
  fi
}

echo "==> Smoke VM123 Finance — $(date -Iseconds)"

# --- Console (Spec 019) — health canónico ---
body=$(curl -sk --connect-timeout 10 "${LAN}:8100/health" 2>/dev/null || true)
if echo "$body" | grep -qiE 'ok|healthy'; then
  pass "Console LAN /health"
else
  fail "Console LAN /health ($(echo "$body" | head -c 40))"
fi

check_code "Console public /health" "https://console.ligbox.com.br/health" "200"
check_code "Console public SPA" "https://console.ligbox.com.br/" "200"

# --- FOSS + Odoo (Docker) ---
check_code "FOSSBilling LAN :8092" "${LAN}:8092/" "200|301|302|403"
check_code "FOSSBilling public /admin" "https://financeiro.ligbox.com.br/admin" "200|301|302|403"
check_code "Odoo LAN /web/login" "${LAN}:8069/web/login" "200|301|302"
check_code "Odoo public login" "https://financeiro.ligbox.com.br/odoo/web/login?db=ligbox" "200|301|302"

# --- OpenPanel (host) ---
check_code "OpenPanel public" "https://openpanel.ligbox.com.br/" "200|301|302|403"
check_code "OpenAdmin public" "https://admin.openpanel.ligbox.com.br/" "200|301|302|403"

# --- Bridge FOSS ↔ OpenPanel (localhost VM123 — porta não exposta LAN) ---
BRIDGE_CODE=$(sshpass -p "${VM123_SSH_PASS:-805353}" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=8 \
  root@10.10.10.123 'curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:18087/api' 2>/dev/null || echo "000")
[[ "$BRIDGE_CODE" =~ ^(200|401|403)$ ]] && pass "OpenPanel bridge :18087 ($BRIDGE_CODE)" || fail "OpenPanel bridge ($BRIDGE_CODE)"

# --- Desk upstream (VM122) — Console depende ---
check_code "Desk API VM122 (upstream)" "http://10.10.10.122:8080/api/health" "200"

echo ""
if [[ "$FAIL" -eq 0 ]]; then
  echo "FINANCE_RELEASE=GREEN"
  exit 0
fi
echo "FINANCE_RELEASE=RED ($FAIL falhas)"
exit 1
