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

ROOT_URL="${ROOT_URL:-https://www.taxbaik.com/}"
ADMIN_URL="${ADMIN_URL:-https://www.taxbaik.com/taxbaik/admin/login}"
PUBLIC_MARKER="${PUBLIC_MARKER:-백원숙 세무회계}"
PUBLIC_FORBIDDEN="${PUBLIC_FORBIDDEN:-관리자}"
ADMIN_MARKER="${ADMIN_MARKER:-관리자 로그인}"
MAX_RETRIES="${MAX_RETRIES:-3}"
RETRY_SLEEP_SECONDS="${RETRY_SLEEP_SECONDS:-5}"

check_page() {
  local url="$1"
  local allow_redirect="${2:-0}"
  local must_contain="${3:-}"
  local must_not_contain="${4:-}"
  local status
  local body

  body=$(curl -fsSL --max-time 15 "$url" 2>/dev/null || true)
  status=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$url" || echo "000")

  if [ "$allow_redirect" = "1" ]; then
    if ! printf '%s' "$status" | grep -Eq '^(200|301|302|303|307|308)$'; then
      echo "  ✗ $url -> HTTP $status" >&2
      return 1
    fi
  elif [ "$status" != "200" ]; then
    echo "  ✗ $url -> HTTP $status" >&2
    return 1
  fi

  if [ -n "$must_contain" ] && ! printf '%s' "$body" | grep -q "$must_contain"; then
    echo "  ✗ $url -> body missing required marker: $must_contain" >&2
    return 1
  fi

  if [ -n "$must_not_contain" ] && printf '%s' "$body" | grep -q "$must_not_contain"; then
    echo "  ✗ $url -> body contains forbidden marker: $must_not_contain" >&2
    return 1
  fi

  echo "  ✓ $url -> HTTP $status"
}

for i in $(seq 1 "$MAX_RETRIES"); do
  if check_page "$ROOT_URL" 1 "$PUBLIC_MARKER" "$PUBLIC_FORBIDDEN" \
    && check_page "${ROOT_URL%/}/taxbaik/" 1 "$PUBLIC_MARKER" "$PUBLIC_FORBIDDEN" \
    && check_page "$ADMIN_URL" 0 "$ADMIN_MARKER" ""; then
    echo "✓ public/admin smoke passed"
    exit 0
  fi

  if [ "$i" -lt "$MAX_RETRIES" ]; then
    echo "  retrying... ($i/$MAX_RETRIES)"
    sleep "$RETRY_SLEEP_SECONDS"
  fi
done

echo "✗ smoke verification failed" >&2
exit 1
