#!/bin/bash
#
# AtlasOS - Calypso VTL Testing Script
# Tests Virtual Tape Library endpoints
#

set -euo pipefail

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

# Configuration
API_URL="${API_URL:-http://localhost:8080}"
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"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Check if token exists
if [ ! -f "$TOKEN_FILE" ]; then
    log_error "No authentication token found."
    log_info "Please login first:"
    log_info "  curl -X POST $API_URL/api/v1/auth/login \\"
    log_info "    -H 'Content-Type: application/json' \\"
    log_info "    -d '{\"username\":\"admin\",\"password\":\"admin123\"}' | jq -r '.token' > $TOKEN_FILE"
    exit 1
fi

TOKEN=$(cat "$TOKEN_FILE")

# Test function
test_endpoint() {
    local method=$1
    local endpoint=$2
    local data=$3
    local description=$4
    
    log_step "Testing: $description"
    
    local cmd="curl -s -w '\nHTTP_CODE:%{http_code}' -H 'Authorization: Bearer $TOKEN'"
    
    if [ "$method" = "POST" ] || [ "$method" = "PUT" ] || [ "$method" = "DELETE" ]; 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"
        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 VTL Testing"
    log_info "=========================================="
    log_info ""
    
    # Test 1: List Libraries (should be empty initially)
    log_info "Test 1: List VTL Libraries"
    LIBRARIES_RESPONSE=$(test_endpoint "GET" "/api/v1/tape/vtl/libraries" "" "List VTL libraries")
    echo ""
    
    # Test 2: Create Library
    log_info "Test 2: Create VTL Library"
    CREATE_DATA='{
        "name": "vtl-test-01",
        "description": "Test Virtual Tape Library",
        "backing_store_path": "/var/lib/calypso/vtl",
        "slot_count": 10,
        "drive_count": 2
    }'
    
    CREATE_RESPONSE=$(test_endpoint "POST" "/api/v1/tape/vtl/libraries" "$CREATE_DATA" "Create VTL library")
    LIBRARY_ID=$(echo "$CREATE_RESPONSE" | jq -r '.id' 2>/dev/null)
    
    if [ -z "$LIBRARY_ID" ] || [ "$LIBRARY_ID" = "null" ]; then
        log_error "Failed to get library ID from create response"
        exit 1
    fi
    
    log_info "Created library with ID: $LIBRARY_ID"
    echo ""
    
    # Test 3: Get Library Details
    log_info "Test 3: Get Library Details"
    test_endpoint "GET" "/api/v1/tape/vtl/libraries/$LIBRARY_ID" "" "Get library details"
    echo ""
    
    # Test 4: List Drives
    log_info "Test 4: List Library Drives"
    test_endpoint "GET" "/api/v1/tape/vtl/libraries/$LIBRARY_ID/drives" "" "List drives"
    echo ""
    
    # Test 5: List Tapes
    log_info "Test 5: List Library Tapes"
    TAPES_RESPONSE=$(test_endpoint "GET" "/api/v1/tape/vtl/libraries/$LIBRARY_ID/tapes" "" "List tapes")
    FIRST_TAPE_ID=$(echo "$TAPES_RESPONSE" | jq -r '.tapes[0].id' 2>/dev/null)
    FIRST_SLOT=$(echo "$TAPES_RESPONSE" | jq -r '.tapes[0].slot_number' 2>/dev/null)
    echo ""
    
    # Test 6: Load Tape
    if [ -n "$FIRST_TAPE_ID" ] && [ "$FIRST_TAPE_ID" != "null" ] && [ -n "$FIRST_SLOT" ]; then
        log_info "Test 6: Load Tape to Drive"
        LOAD_DATA="{\"slot_number\": $FIRST_SLOT, \"drive_number\": 1}"
        LOAD_RESPONSE=$(test_endpoint "POST" "/api/v1/tape/vtl/libraries/$LIBRARY_ID/load" "$LOAD_DATA" "Load tape")
        TASK_ID=$(echo "$LOAD_RESPONSE" | jq -r '.task_id' 2>/dev/null)
        
        if [ -n "$TASK_ID" ] && [ "$TASK_ID" != "null" ]; then
            log_info "Load task created: $TASK_ID"
            log_info "Waiting 2 seconds for task to complete..."
            sleep 2
            
            log_info "Checking task status..."
            test_endpoint "GET" "/api/v1/tasks/$TASK_ID" "" "Get task status"
        fi
        echo ""
    else
        log_warn "Skipping load test - no tapes found"
    fi
    
    # Test 7: Get Library Again (to see updated state)
    log_info "Test 7: Get Library (After Load)"
    test_endpoint "GET" "/api/v1/tape/vtl/libraries/$LIBRARY_ID" "" "Get library after load"
    echo ""
    
    # Test 8: Unload Tape
    if [ -n "$FIRST_SLOT" ]; then
        log_info "Test 8: Unload Tape from Drive"
        UNLOAD_DATA="{\"drive_number\": 1, \"slot_number\": $FIRST_SLOT}"
        UNLOAD_RESPONSE=$(test_endpoint "POST" "/api/v1/tape/vtl/libraries/$LIBRARY_ID/unload" "$UNLOAD_DATA" "Unload tape")
        TASK_ID=$(echo "$UNLOAD_RESPONSE" | jq -r '.task_id' 2>/dev/null)
        
        if [ -n "$TASK_ID" ] && [ "$TASK_ID" != "null" ]; then
            log_info "Unload task created: $TASK_ID"
            log_info "Waiting 2 seconds for task to complete..."
            sleep 2
            
            log_info "Checking task status..."
            test_endpoint "GET" "/api/v1/tasks/$TASK_ID" "" "Get task status"
        fi
        echo ""
    fi
    
    # Test 9: Create Additional Tape
    log_info "Test 9: Create New Tape"
    CREATE_TAPE_DATA='{
        "barcode": "CUSTOM001",
        "slot_number": 11,
        "tape_type": "LTO-8",
        "size_gb": 15000
    }'
    test_endpoint "POST" "/api/v1/tape/vtl/libraries/$LIBRARY_ID/tapes" "$CREATE_TAPE_DATA" "Create new tape"
    echo ""
    
    # Test 10: List Libraries Again
    log_info "Test 10: List Libraries (Final)"
    test_endpoint "GET" "/api/v1/tape/vtl/libraries" "" "List all libraries"
    echo ""
    
    log_info "=========================================="
    log_info "VTL Testing Complete"
    log_info "=========================================="
    log_info ""
    log_info "Library ID: $LIBRARY_ID"
    log_info "You can continue testing with:"
    log_info "  export LIBRARY_ID=$LIBRARY_ID"
    log_info ""
    log_warn "Note: Library deletion test skipped (use DELETE endpoint manually if needed)"
    log_info ""
}

# Run tests
main

