#!/bin/bash
BASE_URL="http://localhost:8080/api"
TOKEN=""
PASS_COUNT=0
FAIL_COUNT=0
TOTAL_COUNT=0

assert_eq() {
  local actual="$1"
  local expected="$2"
  local name="$3"
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  if [ "$actual" = "$expected" ]; then
    echo "  PASS: $name"
    PASS_COUNT=$((PASS_COUNT + 1))
  else
    echo "  FAIL: $name (expected=$expected, actual=$actual)"
    FAIL_COUNT=$((FAIL_COUNT + 1))
  fi
}

assert_contains() {
  local haystack="$1"
  local needle="$2"
  local name="$3"
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  if echo "$haystack" | grep -q "$needle"; then
    echo "  PASS: $name"
    PASS_COUNT=$((PASS_COUNT + 1))
  else
    echo "  FAIL: $name (expected to contain: $needle)"
    FAIL_COUNT=$((FAIL_COUNT + 1))
  fi
}

assert_not_contains() {
  local haystack="$1"
  local needle="$2"
  local name="$3"
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  if echo "$haystack" | grep -q "$needle"; then
    echo "  FAIL: $name (expected NOT to contain: $needle)"
    FAIL_COUNT=$((FAIL_COUNT + 1))
  else
    echo "  PASS: $name"
    PASS_COUNT=$((PASS_COUNT + 1))
  fi
}

login() {
  echo "=== 登录获取Token ==="
  local response=$(curl -s -X POST "$BASE_URL/auth/login" \
    -H "Content-Type: application/json" \
    -d '{"username":"admin","password":"admin123"}')
  TOKEN=$(echo "$response" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
  if [ -z "$TOKEN" ]; then
    echo "FATAL: 登录失败，无法获取Token"
    echo "Response: $response"
    exit 1
  fi
  echo "Token获取成功"
}

test_login_success() {
  echo "--- TC-AUTH-001: 用户登录-正常 ---"
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/login" \
    -H "Content-Type: application/json" \
    -d '{"username":"admin","password":"admin123"}')
  local status=$(echo "$response" | tail -n 1)
  local body=$(echo "$response" | head -n -1)
  assert_eq "$status" "200" "TC-AUTH-001: 登录返回200"
  assert_contains "$body" '"token"' "TC-AUTH-001: 响应包含token"
  assert_contains "$body" '"userId"' "TC-AUTH-001: 响应包含userId"
  assert_contains "$body" '"roles"' "TC-AUTH-001: 响应包含roles"
}

test_login_wrong_password() {
  echo "--- TC-AUTH-002: 用户登录-密码错误 ---"
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/login" \
    -H "Content-Type: application/json" \
    -d '{"username":"admin","password":"wrongpassword"}')
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "401" "TC-AUTH-002: 错误密码返回401"
}

test_login_lockout() {
  echo "--- TC-AUTH-003: 用户登录-锁定机制 ---"
  local test_user="lockout_test_$$"
  curl -s -X POST "$BASE_URL/auth/users" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"username\":\"$test_user\",\"password\":\"Test@1234\",\"userType\":\"ENTERPRISE\"}" > /dev/null 2>&1
  for i in $(seq 1 5); do
    curl -s -X POST "$BASE_URL/auth/login" \
      -H "Content-Type: application/json" \
      -d "{\"username\":\"$test_user\",\"password\":\"wrong$i\"}" > /dev/null 2>&1
  done
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/login" \
    -H "Content-Type: application/json" \
    -d "{\"username\":\"$test_user\",\"password\":\"Test@1234\"}")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "401" "TC-AUTH-003: 5次失败后账户锁定"
}

test_get_current_user() {
  echo "--- TC-AUTH-005: 获取当前用户 ---"
  local response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/auth/me" \
    -H "Authorization: Bearer $TOKEN")
  local status=$(echo "$response" | tail -n 1)
  local body=$(echo "$response" | head -n -1)
  assert_eq "$status" "200" "TC-AUTH-005: 获取当前用户返回200"
  assert_contains "$body" '"username"' "TC-AUTH-005: 响应包含username"
}

test_refresh_token() {
  echo "--- TC-AUTH-004: Token刷新 ---"
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/refresh" \
    -H "Authorization: Bearer $TOKEN")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-AUTH-004: Token刷新返回200"
}

test_logout() {
  echo "--- TC-AUTH-006: 用户登出 ---"
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/logout" \
    -H "Authorization: Bearer $TOKEN")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-AUTH-006: 登出返回200"
}

test_create_user() {
  echo "--- TC-AUTH-007: 创建用户 ---"
  local username="testuser_$$"
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/users" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"username\":\"$username\",\"password\":\"Test@1234\",\"userType\":\"ENTERPRISE\",\"realName\":\"Test User\"}")
  local status=$(echo "$response" | tail -n 1)
  local body=$(echo "$response" | head -n -1)
  assert_eq "$status" "201" "TC-AUTH-007: 创建用户返回201"
  CREATED_USER_ID=$(echo "$body" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
}

test_list_users() {
  echo "--- TC-AUTH-008: 查询用户列表 ---"
  local response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/auth/users?page=0&size=10" \
    -H "Authorization: Bearer $TOKEN")
  local status=$(echo "$response" | tail -n 1)
  local body=$(echo "$response" | head -n -1)
  assert_eq "$status" "200" "TC-AUTH-008: 查询用户列表返回200"
  assert_contains "$body" '"content"' "TC-AUTH-008: 响应包含content"
}

test_update_user() {
  echo "--- TC-AUTH-009: 更新用户 ---"
  if [ -z "$CREATED_USER_ID" ]; then
    echo "  SKIP: TC-AUTH-009 (无用户ID)"
    return
  fi
  local response=$(curl -s -w "\n%{http_code}" -X PUT "$BASE_URL/auth/users/$CREATED_USER_ID" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{"realName":"Updated Name","phone":"13800138000"}')
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-AUTH-009: 更新用户返回200"
}

test_delete_user() {
  echo "--- TC-AUTH-010: 删除用户 ---"
  if [ -z "$CREATED_USER_ID" ]; then
    echo "  SKIP: TC-AUTH-010 (无用户ID)"
    return
  fi
  local response=$(curl -s -w "\n%{http_code}" -X DELETE "$BASE_URL/auth/users/$CREATED_USER_ID" \
    -H "Authorization: Bearer $TOKEN")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-AUTH-010: 删除用户返回200"
}

test_weak_password_rejected() {
  echo "--- TC-AUTH-012: 弱密码拒绝 ---"
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/users" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{"username":"weakpwd_$$_test","password":"123456","userType":"ENTERPRISE"}')
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "400" "TC-AUTH-012: 弱密码返回400"
}

test_create_role() {
  echo "--- TC-AUTH-013: 创建角色 ---"
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/roles" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"code\":\"TEST_ROLE_$$\",\"name\":\"Test Role\",\"type\":\"SYSTEM\"}")
  local status=$(echo "$response" | tail -n 1)
  local body=$(echo "$response" | head -n -1)
  assert_eq "$status" "201" "TC-AUTH-013: 创建角色返回201"
  CREATED_ROLE_ID=$(echo "$body" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
}

test_assign_role_permissions() {
  echo "--- TC-AUTH-014: 角色权限分配 ---"
  if [ -z "$CREATED_ROLE_ID" ]; then
    echo "  SKIP: TC-AUTH-014 (无角色ID)"
    return
  fi
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/roles/$CREATED_ROLE_ID/permissions" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{"permissionIds":[]}')
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-AUTH-014: 角色权限分配返回200"
}

test_create_permission() {
  echo "--- TC-AUTH-015: 创建权限 ---"
  local response=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/auth/permissions" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"code\":\"test:resource:action_$$\",\"name\":\"Test Permission\",\"type\":\"API\"}")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "201" "TC-AUTH-015: 创建权限返回201"
}

test_dept_tree() {
  echo "--- TC-AUTH-016: 部门树查询 ---"
  local response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/auth/depts/tree" \
    -H "Authorization: Bearer $TOKEN")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-AUTH-016: 部门树查询返回200"
}

test_audit_log_query() {
  echo "--- TC-AUTH-020: 审计日志查询 ---"
  local response=$(curl -s -w "\n%{http_code}" -X GET "$BASE_URL/auth/audit-logs?page=0&size=10" \
    -H "Authorization: Bearer $TOKEN")
  local status=$(echo "$response" | tail -n 1)
  assert_eq "$status" "200" "TC-AUTH-020: 审计日志查询返回200"
}

cleanup() {
  echo "=== 清理测试数据 ==="
  if [ -n "$CREATED_ROLE_ID" ]; then
    curl -s -X DELETE "$BASE_URL/auth/roles/$CREATED_ROLE_ID" \
      -H "Authorization: Bearer $TOKEN" > /dev/null 2>&1
  fi
}

print_summary() {
  echo ""
  echo "=========================================="
  echo "  Auth Domain API Test Summary"
  echo "=========================================="
  echo "  Total:  $TOTAL_COUNT"
  echo "  Passed: $PASS_COUNT"
  echo "  Failed: $FAIL_COUNT"
  if [ "$TOTAL_COUNT" -gt 0 ]; then
    local rate=$(echo "scale=1; $PASS_COUNT * 100 / $TOTAL_COUNT" | bc)
    echo "  Rate:   ${rate}%"
  fi
  echo "=========================================="
  if [ "$FAIL_COUNT" -gt 0 ]; then
    return 1
  fi
  return 0
}

CREATED_USER_ID=""
CREATED_ROLE_ID=""

echo "=========================================="
echo "  Ether PMS - Auth Domain API Tests"
echo "=========================================="
echo ""

login

test_login_success
test_login_wrong_password
test_login_lockout
test_get_current_user
test_refresh_token
test_create_user
test_list_users
test_update_user
test_weak_password_rejected
test_create_role
test_assign_role_permissions
test_create_permission
test_dept_tree
test_delete_user
test_audit_log_query
test_logout

cleanup
print_summary
