#!/bin/bash
#
# 未登录访问测试
# 测试内容：验证受保护接口在未登录状态下拒绝访问
#

set -e

# 加载公共库
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib.sh"

test_start "未登录访问测试 (None Auth)"

# 检查服务
check_service

# 定义要测试的受保护接口列表
# 格式: "METHOD PATH [BODY]"
PROTECTED_ENDPOINTS=(
    "GET /api/auth/me"
    "POST /api/auth/logout {}"
    "GET /api/users"
    "POST /api/users {}"
    "GET /api/orgs"
    "POST /api/orgs {}"
    "GET /api/roles"
    "POST /api/roles {}"
    "GET /api/settings"
    "GET /api/oauth/clients"
    "GET /api/oauth/providers"
)

# 遍历测试
for endpoint in "${PROTECTED_ENDPOINTS[@]}"; do
    read -r method path body <<< "$endpoint"
    
    step "测试 $method $path (未登录)"
    
    if [ "$method" == "GET" ]; then
        RES=$(api_get "$path" "")
    elif [ "$method" == "POST" ]; then
        RES=$(api_post "$path" "${body:-{}}" "")
    elif [ "$method" == "PATCH" ]; then
        RES=$(api_patch "$path" "${body:-{}}" "")
    elif [ "$method" == "DELETE" ]; then
        RES=$(api_delete "$path" "")
    fi
    
    # 提取状态码
    # 注意：Vigo 框架可能返回 HTTP 401 或 JSON code 40100
    # check_http_code 默认提取 JSON 中的 code
    code=$(echo "$RES" | jq -r '.code // 200')
    
    # 允许 401 (Standard HTTP) 或 40100 (Vigo Unauthorized)
    if [[ "$code" == "401" || "$code" == "40100" ]]; then
        success "访问被拒绝 (Code: $code)"
    else
        error "期望 401/40100, 实际: $code"
        info "响应: $RES"
        # 标记失败但不立即退出，以便测试所有接口? 
        # 这里为了严格性，还是退出吧，或者用 fail_flag
        exit 1
    fi
done

test_end
