#!/usr/bin/env bash
# Phase 1: Base API Test
# Modules: 01_auth, 02_health, 13_config, 11_error_codes, 12_agent
# Endpoints: 15

BASE="https://m5api.momentry.ddns.net"
API_KEY="muser_68600856036340bcafc01930eb4bd839_1774418104_97221b69"
FILE_UUID="a6fb22eebefaef17e62af874997c5944"

PASS=0
FAIL=0
TOTAL=0

echo "============================================"
echo " Phase 1: Base API Test"
echo " Base:    $BASE"
echo " File:    $FILE_UUID"
echo "============================================"
echo ""

test_api() {
    local method="$1" path="$2" auth="$3" body="$4" desc="$5"
    TOTAL=$((TOTAL+1))

    local tmpfile="/tmp/m5api_resp_${TOTAL}.json"
    local curl_args=(-s -o "$tmpfile" -w "\nHTTP:%{http_code}")
    curl_args+=(-X "$method")
    curl_args+=(-H "Content-Type: application/json")
    curl_args+=(-H "X-API-Key: $API_KEY")

    if [ -n "$body" ]; then
        curl_args+=(-d "$body")
    fi

    local result
    result=$(curl "${curl_args[@]}" "${BASE}${path}" 2>/dev/null)
    local code=$(echo "$result" | grep "HTTP:" | tr -d "HTTP:")
    local resp_body=$(echo "$result" | sed '/^HTTP:/d')
    local size=${#resp_body}

    if [ "$code" -ge 200 ] 2>/dev/null && [ "$code" -lt 400 ] 2>/dev/null; then
        PASS=$((PASS+1))
        printf "  ✅ %2d. %-5s %-50s → %s (%d B) — %s\n" "$TOTAL" "$method" "$path" "$code" "$size" "$desc"
    else
        FAIL=$((FAIL+1))
        printf "  ❌ %2d. %-5s %-50s → %s (%d B) — %s\n" "$TOTAL" "$method" "$path" "$code" "$size" "$desc"
        local preview
        preview=$(echo "$resp_body" | head -c 150)
        echo "      $preview"
    fi
}

# Auth — no auth header needed for these two
test_api_no_key() {
    local method="$1" path="$2" body="$3" desc="$4"
    TOTAL=$((TOTAL+1))

    local tmpfile="/tmp/m5api_resp_${TOTAL}.json"
    local curl_args=(-s -o "$tmpfile" -w "\nHTTP:%{http_code}")
    curl_args+=(-X "$method")
    curl_args+=(-H "Content-Type: application/json")

    if [ -n "$body" ]; then
        curl_args+=(-d "$body")
    fi

    local result
    result=$(curl "${curl_args[@]}" "${BASE}${path}" 2>/dev/null)
    local code=$(echo "$result" | grep "HTTP:" | tr -d "HTTP:")
    local resp_body=$(echo "$result" | sed '/^HTTP:/d')
    local size=${#resp_body}

    if [ "$code" -ge 200 ] 2>/dev/null && [ "$code" -lt 400 ] 2>/dev/null; then
        PASS=$((PASS+1))
        printf "  ✅ %2d. %-5s %-50s → %s (%d B) — %s\n" "$TOTAL" "$method" "$path" "$code" "$size" "$desc"
    else
        FAIL=$((FAIL+1))
        printf "  ❌ %2d. %-5s %-50s → %s (%d B) — %s\n" "$TOTAL" "$method" "$path" "$code" "$size" "$desc"
        local preview
        preview=$(echo "$resp_body" | head -c 150)
        echo "      $preview"
    fi
}

echo "── Auth ──"
test_api_no_key "POST" "/api/v1/auth/login" '{"username":"demo","password":"demo"}' "Demo login"
test_api_no_key "POST" "/api/v1/auth/logout" "" "Logout"

echo ""
echo "── Health ──"
test_api "GET" "/health" "yes" "" "Basic health"
test_api "GET" "/health/detailed" "yes" "" "Detailed health"
test_api "GET" "/health/consistency" "yes" "" "Consistency check"

echo ""
echo "── Config ──"
test_api "POST" "/api/v1/config/cache" "yes" '{"enabled":true}' "Cache toggle"
test_api "POST" "/api/v1/config/auto-pipeline" "yes" '{"enabled":false}' "Auto-pipeline toggle"
test_api "POST" "/api/v1/config/watcher-auto-register" "yes" '{"enabled":false}' "Watcher auto-register"

echo ""
echo "── Stats ──"
test_api "GET" "/api/v1/stats/sftpgo" "yes" "" "SFTPGo status"
test_api "GET" "/api/v1/stats/ingestion-status/$FILE_UUID" "yes" "" "Ingestion status"

echo ""
echo "── Resources ──"
test_api "GET" "/api/v1/resources" "yes" "" "List resources"
test_api "POST" "/api/v1/resource/register" "yes" '{"resource_id":"test_phase1","resource_type":"test","category":"test"}' "Register resource"
test_api "POST" "/api/v1/resource/heartbeat" "yes" '{"resource_id":"test"}' "Heartbeat"

echo ""
echo "── Jobs ──"
test_api "GET" "/api/v1/jobs?page=1&page_size=3" "yes" "" "List jobs"

echo ""
echo "── Media ──"
test_api_no_key "POST" "/api/v1/search/visual" "{\"file_uuid\":\"$FILE_UUID\",\"criteria\":{}}" "Visual search (POST)"

echo ""
echo "============================================"
echo " Total:  $TOTAL"
echo " Passed: $PASS ✅"
echo " Failed: $FAIL ❌"
echo "============================================"

if [ $FAIL -gt 0 ]; then
    echo "❌ Phase 1 FAILED"
    exit 1
else
    echo "✅ Phase 1 PASSED"
fi
