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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
APP_DIR="$ROOT_DIR/app"
LOCAL_ENV_FILE="${TDC114_SMOKE_ENV_FILE:-$ROOT_DIR/scripts/.env.smoke.local}"
ANDROID_PREFLIGHT_SCRIPT="${TDC114_ANDROID_PREFLIGHT_SCRIPT:-$ROOT_DIR/scripts/check-android-device-env.sh}"

if [ -f "$LOCAL_ENV_FILE" ]; then
  # shellcheck disable=SC1090
  source "$LOCAL_ENV_FILE"
fi

if [ -z "${TDC114_API_BASE:-}" ]; then
  echo "TDC114_API_BASE is required for integration tests." >&2
  echo "Example: TDC114_API_BASE=https://staging.example.com $0" >&2
  if [ -f "$LOCAL_ENV_FILE" ]; then
    echo "Loaded local smoke env from $LOCAL_ENV_FILE" >&2
  fi
  exit 64
fi

if [ ! -d "$APP_DIR/integration_test" ]; then
  echo "integration test scaffold: $APP_DIR/integration_test does not exist yet." >&2
  echo "Add Flutter integration tests before enabling this script in CI." >&2
  exit 2
fi

if [ -n "${TDC114_ADB_CONNECT_ADDRESS:-}" ] || [ -n "${TDC114_FLUTTER_DEVICE_ID:-}" ] || [ -n "${ADB_SERVER_SOCKET:-}" ]; then
  "$ANDROID_PREFLIGHT_SCRIPT"
fi

TEST_ARGS=(
  "drive"
  "--dart-define=TDC114_API_BASE=${TDC114_API_BASE}"
)

append_optional_define() {
  local key="$1"
  local value="${!key:-}"
  if [ -n "$value" ]; then
    TEST_ARGS+=("--dart-define=${key}=${value}")
  fi
}

append_optional_define "SSO_BASE_URL"
append_optional_define "TDC114_AUTH_API_BASE"
append_optional_define "TDC114_DIRECTORY_API_BASE"
append_optional_define "TDC114_ORGANIZATION_API_BASE"
append_optional_define "TDC114_ORG_CONTEXT_API_BASE"
append_optional_define "TDC114_ORG_CONTEXT_TENANT_SLUG"

TEST_DEVICE_ID="${TDC114_FLUTTER_DEVICE_ID:-${TDC114_ADB_CONNECT_ADDRESS:-}}"
if [ -n "$TEST_DEVICE_ID" ]; then
  TEST_ARGS+=("-d" "$TEST_DEVICE_ID")
fi

if [ "${TDC114_SMOKE_ASSUME_LOGGED_IN:-}" = "1" ] || [ "${TDC114_SMOKE_ASSUME_LOGGED_IN:-}" = "true" ]; then
  TEST_ARGS+=("--dart-define=TDC114_SMOKE_ASSUME_LOGGED_IN=true")
  bootstrap_mode="${TDC114_SESSION_BOOTSTRAP_MODE:-mock}"
  preauth_exports=""

  if [ -z "${TDC114_SMOKE_PHONE:-}" ]; then
    TDC114_SMOKE_PHONE=01012345678
  fi

  if [ "$bootstrap_mode" = "legacy-phone-login" ]; then
    bootstrap_api_base="${TDC114_SESSION_BOOTSTRAP_API_BASE:-$TDC114_API_BASE}"
    bootstrap_api_base="${bootstrap_api_base//10.0.2.2/127.0.0.1}"
    bootstrap_api_base="${bootstrap_api_base//localhost/127.0.0.1}"

    login_payload="$(printf '{"phoneNumber":"%s","device":{"platform":"android","appVersion":"integration-smoke","deviceName":"android-bootstrap"}}' "$TDC114_SMOKE_PHONE")"
    set +e
    login_response="$(
      curl -fsS \
        -H 'content-type: application/json' \
        -d "$login_payload" \
        "${bootstrap_api_base%/}/api/v1/tdc114plus/auth/phone-login" 2>/tmp/tdc114plus_integration_bootstrap.err
    )"
    bootstrap_status=$?
    set -e

    if [ "$bootstrap_status" -eq 0 ]; then
      preauth_exports="$(
        python3 -c '
import json, sys
data = json.loads(sys.argv[1])
user = data.get("user") or {}
fields = {
    "TDC114_PREAUTH_TOKEN": data.get("token", ""),
    "TDC114_PREAUTH_EXPIRES_AT": data.get("expiresAt", ""),
    "TDC114_PREAUTH_USER_ID": user.get("id", ""),
    "TDC114_PREAUTH_USER_NAME": user.get("name", ""),
    "TDC114_PREAUTH_USER_PHONE": user.get("phoneNumber", ""),
    "TDC114_PREAUTH_TENANT_ID": user.get("tenantId", ""),
    "TDC114_PREAUTH_TENANT_NAME": user.get("tenantName", ""),
    "TDC114_PREAUTH_TENANT_SLUG": user.get("tenantSlug", ""),
    "TDC114_PREAUTH_DEPARTMENT": user.get("department", ""),
    "TDC114_PREAUTH_GRADE": user.get("grade", ""),
    "TDC114_PREAUTH_POSITION": user.get("position", ""),
    "TDC114_PREAUTH_JOB_TITLE": user.get("jobTitle", ""),
}
for key, value in fields.items():
    if value is None:
        value = ""
    print(f"{key}={value}")
' "$login_response"
      )"
    else
      echo "WARN legacy integration bootstrap phone-login failed; falling back to mock directory mode." >&2
      cat /tmp/tdc114plus_integration_bootstrap.err >&2 || true
    fi
  else
    echo "INFO integration session bootstrap uses mock mode by default under the current headless-login policy." >&2
  fi

  if [ -z "$preauth_exports" ]; then
    preauth_exports="$(cat <<'EOF'
TDC114_PREAUTH_TOKEN=mock-session-token
TDC114_PREAUTH_EXPIRES_AT=2099-12-31T23:59:59Z
TDC114_PREAUTH_USER_ID=user-001
TDC114_PREAUTH_USER_NAME=김하늘
TDC114_PREAUTH_USER_PHONE=+821012345678
TDC114_PREAUTH_TENANT_ID=tenant-hanmac
TDC114_PREAUTH_TENANT_NAME=한맥
TDC114_PREAUTH_TENANT_SLUG=hanmac
TDC114_PREAUTH_DEPARTMENT=기술연구소
TDC114_PREAUTH_GRADE=책임
TDC114_PREAUTH_POSITION=팀장
TDC114_PREAUTH_JOB_TITLE=Flutter 개발
EOF
)"
    TEST_ARGS+=("--dart-define=TDC114_SMOKE_USE_MOCK_DIRECTORY=true")
  fi

  while IFS='=' read -r key value; do
    [ -n "$key" ] || continue
    TEST_ARGS+=("--dart-define=${key}=${value}")
  done <<< "$preauth_exports"
fi

if [ -n "${TDC114_SMOKE_PHONE:-}" ]; then
  TEST_ARGS+=("--dart-define=TDC114_SMOKE_PHONE=${TDC114_SMOKE_PHONE}")
fi

if [ -n "${TDC114_SMOKE_EXPECTED_NAME:-}" ]; then
  TEST_ARGS+=("--dart-define=TDC114_SMOKE_EXPECTED_NAME=${TDC114_SMOKE_EXPECTED_NAME}")
fi

if [ -n "${TDC114_SMOKE_EXPECTED_TENANT_LABEL:-}" ]; then
  TEST_ARGS+=("--dart-define=TDC114_SMOKE_EXPECTED_TENANT_LABEL=${TDC114_SMOKE_EXPECTED_TENANT_LABEL}")
fi

TEST_ARGS+=(
  "--driver=test_driver/integration_driver.dart"
  "--target=integration_test/app_smoke_test.dart"
)

OUTPUT_FILE="$(mktemp)"
trap 'rm -f "$OUTPUT_FILE"' EXIT

set +e
"$ROOT_DIR/scripts/flutter-docker.sh" "${TEST_ARGS[@]}" 2>&1 | tee "$OUTPUT_FILE"
status=$?
set -e

if [ "$status" -ne 0 ] && grep -q "No supported devices connected." "$OUTPUT_FILE"; then
  echo >&2
  echo "integration test requires a supported runtime target." >&2
  echo "Current Flutter project only has Android/iOS runners." >&2
  echo "Connect an Android physical device first, or use an emulator fallback, before retrying." >&2
  exit 2
fi

exit "$status"
