#!/bin/bash

set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
URL="${1:-http://127.0.0.1:7703}"

# Use test tokens from environment or defaults
TOKEN="${TEST_TOKEN1:-t570H7DmK2VBfCwUmtFaUXyzVklL90E1}"

echo "Testing basic input validation at $URL"
echo "======================================"

PASS_COUNT=0
FAIL_COUNT=0

# Helper function to test an upload with expected result
test_upload() {
    local test_name="$1"
    local metadata="$2"
    local expected_result="$3"  # "success" or "error"
    
    echo ""
    echo "Test: $test_name"
    
    # Create a temp file
    local temp_file="/tmp/test_$$"
    echo "test content" > "$temp_file"
    
    # Perform upload with timeout
    local response=$(curl -s --max-time 5 -X PUT \
        -H "Authorization: Bearer $TOKEN" \
        -F "file=@$temp_file" \
        -F "metadata=$metadata" \
        "$URL/upload" 2>&1)
    
    rm -f "$temp_file"
    
    local result=$(echo "$response" | jq -r '.result' 2>/dev/null || echo "parse_error")
    
    if [ "$expected_result" = "error" ]; then
        if [ "$result" = "error" ]; then
            echo "  ✓ Correctly rejected"
            PASS_COUNT=$((PASS_COUNT + 1))
        else
            echo "  ✗ FAILED: Expected rejection"
            FAIL_COUNT=$((FAIL_COUNT + 1))
        fi
    else
        if [ "$result" = "success" ]; then
            echo "  ✓ Correctly accepted"
            PASS_COUNT=$((PASS_COUNT + 1))
        else
            echo "  ✗ FAILED: Expected success"
            FAIL_COUNT=$((FAIL_COUNT + 1))
        fi
    fi
}

echo ""
echo "Testing Label:Tag Validation"
echo "============================="

# Valid label:tag
test_upload "Valid label:tag" '{"labeltags":["test:v1"]}' "success"

# Invalid: missing colon
test_upload "Missing colon" '{"labeltags":["testv1"]}' "error"

# Invalid: empty label
test_upload "Empty label" '{"labeltags":[":v1"]}' "error"

# Invalid: empty tag
test_upload "Empty tag" '{"labeltags":["test:"]}' "error"

# Invalid: special characters
test_upload "Invalid characters" '{"labeltags":["test@#$:v1"]}' "error"

# Invalid: starts with non-alphanumeric
test_upload "Starts with dash" '{"labeltags":["-test:v1"]}' "error"

# Valid: with allowed special chars
test_upload "Valid special chars" '{"labeltags":["test_project-1.0:v1"]}' "success"

# Invalid: too long label (>255 chars) - simplified version (256 chars)
LONG_STR="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
test_upload "Label too long" "{\"labeltags\":[\"${LONG_STR}:v1\"]}" "error"

# Invalid: duplicate labeltags
test_upload "Duplicate labeltags" '{"labeltags":["test:v1","test:v1"]}' "error"

echo ""
echo "Testing Metadata Validation"
echo "============================"

# Valid metadata with various fields
test_upload "Valid metadata" '{"labeltags":["test:meta1"],"custom_field":"value","number":123}' "success"

# Invalid: field name with invalid characters
test_upload "Invalid field name" '{"labeltags":["test:meta2"],"field-with-dash":"value"}' "error"

# Invalid: field name starting with number
test_upload "Field starts with number" '{"labeltags":["test:meta3"],"123field":"value"}' "error"

echo ""
echo "Testing Filename Validation"
echo "============================"

# Invalid: directory traversal
test_upload "Directory traversal" '{"labeltags":["test:file1"],"filename":"../etc/passwd"}' "error"

# Invalid: path separator
test_upload "Path separator" '{"labeltags":["test:file3"],"filename":"path/to/file.txt"}' "error"

echo ""
echo "======================================"
echo "Test Results:"
echo "  Passed: $PASS_COUNT"
echo "  Failed: $FAIL_COUNT"
echo ""

if [ $FAIL_COUNT -eq 0 ]; then
    echo "✓ All input validation tests passed!"
    exit 0
else
    echo "✗ Some tests failed"
    exit 1
fi