#!/usr/bin/env bash
# Spec 027 Fase 3 — VM123 integration smoke test
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${ENV_FILE:-/opt/ligbox-ops-platform/.env}"
if [[ -f "$ENV_FILE" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$ENV_FILE"
  set +a
fi

API="${API_URL:-http://10.10.10.122:8080}"
PASS="${DESK_BOOTSTRAP_PASSWORD:-805353}"
ODOO_URL="${ODOO_URL:-http://10.10.10.123:8069}"

echo "=== verify-vm123-integration.sh ==="

fail() { echo "FAIL: $1"; exit 1; }
ok() { echo "OK: $1"; }

python3 "$ROOT/api/tests/test_permissions_027.py" || fail "permissions unit tests"
ok "RBAC unit tests"

curl -sf --max-time 5 "${ODOO_URL}/web/health" | grep -q pass || fail "Odoo health LAN"
ok "Odoo health ${ODOO_URL}"

login_token() {
  curl -sf -X POST "$API/api/v1/auth/login" \
    -H "Content-Type: application/json" \
    -d "{\"username\":\"$1\",\"password\":\"$PASS\"}" \
    | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])"
}

TOKEN=$(login_token root)
ok "login root"

curl -sf -H "Authorization: Bearer $TOKEN" \
  "$API/api/v1/vm123/odoo/role-model/sales_admin" \
  | python3 -c "
import json,sys
d=json.load(sys.stdin)
assert d.get('role')=='sales_admin'
print('installed', d.get('installed_sales_account_modules'))
" || fail "odoo role-model"
ok "GET /vm123/odoo/role-model/sales_admin"

code=$(curl -s -o /dev/null -w '%{http_code}' \
  -H "Authorization: Bearer $TOKEN" \
  "$API/api/v1/vm123/links/client?domain=test.ligbox.com.br")
[[ "$code" == "200" ]] || fail "vm123 links (got $code)"
ok "GET /vm123/links/client"

echo "=== verify-vm123-integration.sh PASSED ==="
