#!/bin/bash
#
# AtlasOS - Calypso API Testing Script
# This script tests the implemented API endpoints
#

set -euo pipefail

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
API_URL="${API_URL:-http://localhost:8080}"
ADMIN_USER="${ADMIN_USER:-admin}"
ADMIN_PASS="${ADMIN_PASS:-admin123}"
TOKEN_FILE="/tmp/calypso-test-token"

# Helper functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

# Test function
test_endpoint() {
    local method=$1
    local endpoint=$2
    local data=$3
    local description=$4
    local requires_auth=${5:-true}

    log_info "Testing: $description"
    
    local cmd="curl -s -w '\nHTTP_CODE:%{http_code}'"
    
    if [ "$requires_auth" = "true" ]; then
        if [ ! -f "$TOKEN_FILE" ]; then
            log_error "No authentication token found. Run login first."
            return 1
        fi
        local token=$(cat "$TOKEN_FILE")
        cmd="$cmd -H 'Authorization: Bearer $token'"
    fi
    
    if [ "$method" = "POST" ] || [ "$method" = "PUT" ]; then
        cmd="$cmd -X $method -H 'Content-Type: application/json'"
        if [ -n "$data" ]; then
            cmd="$cmd -d '$data'"
        fi
    else
        cmd="$cmd -X $method"
    fi
    
    cmd="$cmd '$API_URL$endpoint'"
    
    local response=$(eval $cmd)
    local http_code=$(echo "$response" | grep -oP 'HTTP_CODE:\K\d+')
    local body=$(echo "$response" | sed 's/HTTP_CODE:[0-9]*$//')
    
    if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 300 ]; then
        log_info "✓ Success (HTTP $http_code)"
        echo "$body" | jq . 2>/dev/null || echo "$body"
        return 0
    else
        log_error "✗ Failed (HTTP $http_code)"
        echo "$body" | jq . 2>/dev/null || echo "$body"
        return 1
    fi
}

# Main test flow
main() {
    log_info "=========================================="
    log_info "AtlasOS - Calypso API Testing"
    log_info "=========================================="
    log_info ""
    
    # Test 1: Health Check
    log_info "Test 1: Health Check"
    if test_endpoint "GET" "/api/v1/health" "" "Health check" false; then
        log_info "✓ API is running"
    else
        log_error "✗ API is not responding. Is it running?"
        exit 1
    fi
    echo ""
    
    # Test 2: Login
    log_info "Test 2: User Login"
    login_data="{\"username\":\"$ADMIN_USER\",\"password\":\"$ADMIN_PASS\"}"
    response=$(curl -s -X POST "$API_URL/api/v1/auth/login" \
        -H "Content-Type: application/json" \
        -d "$login_data")
    
    token=$(echo "$response" | jq -r '.token' 2>/dev/null)
    if [ -n "$token" ] && [ "$token" != "null" ]; then
        echo "$token" > "$TOKEN_FILE"
        log_info "✓ Login successful"
        echo "$response" | jq .
    else
        log_error "✗ Login failed"
        echo "$response" | jq . 2>/dev/null || echo "$response"
        log_warn "Note: You may need to create the admin user in the database first"
        exit 1
    fi
    echo ""
    
    # Test 3: Get Current User
    log_info "Test 3: Get Current User"
    test_endpoint "GET" "/api/v1/auth/me" "" "Get current user info"
    echo ""
    
    # Test 4: List Disks
    log_info "Test 4: List Physical Disks"
    test_endpoint "GET" "/api/v1/storage/disks" "" "List physical disks"
    echo ""
    
    # Test 5: List Volume Groups
    log_info "Test 5: List Volume Groups"
    test_endpoint "GET" "/api/v1/storage/volume-groups" "" "List volume groups"
    echo ""
    
    # Test 6: List Repositories
    log_info "Test 6: List Repositories"
    test_endpoint "GET" "/api/v1/storage/repositories" "" "List repositories"
    echo ""
    
    # Test 7: List SCST Handlers (may fail if SCST not installed)
    log_info "Test 7: List SCST Handlers"
    if test_endpoint "GET" "/api/v1/scst/handlers" "" "List SCST handlers"; then
        log_info "✓ SCST handlers detected"
    else
        log_warn "✗ SCST handlers not available (SCST may not be installed)"
    fi
    echo ""
    
    # Test 8: List SCST Targets
    log_info "Test 8: List SCST Targets"
    test_endpoint "GET" "/api/v1/scst/targets" "" "List SCST targets"
    echo ""
    
    # Test 9: List System Services
    log_info "Test 9: List System Services"
    test_endpoint "GET" "/api/v1/system/services" "" "List system services"
    echo ""
    
    # Test 10: Get Service Status
    log_info "Test 10: Get Service Status"
    test_endpoint "GET" "/api/v1/system/services/calypso-api" "" "Get calypso-api service status"
    echo ""
    
    # Test 11: List Users (Admin only)
    log_info "Test 11: List Users (Admin)"
    test_endpoint "GET" "/api/v1/iam/users" "" "List users"
    echo ""
    
    log_info "=========================================="
    log_info "Testing Complete"
    log_info "=========================================="
    log_info ""
    log_info "Token saved to: $TOKEN_FILE"
    log_info "You can use this token for manual testing:"
    log_info "  export TOKEN=\$(cat $TOKEN_FILE)"
    log_info ""
}

# Run tests
main

