#!/bin/bash
# Test import tools validation
# Usage: ./test_import.sh
# Uses fresh copy of production DB in /tmp (auto-cleaned)

source "$(dirname "$0")/test_lib.sh"

echo "=== Testing Import Tools ==="
echo ""

check_binary

# Create fresh test database
DB_PATH=$(fresh_test_db)
trap "cleanup_test_db '$DB_PATH'" EXIT
echo "Using fresh test database: $DB_PATH"
echo ""

# Get test IDs from database
echo "Setup: Getting test IDs from database"
DATASET_RESULT=$(send_request "tools/call" '{"name":"execute_sql","arguments":{"query":"SELECT id, name FROM dataset WHERE active = true LIMIT 1"}}' "$DB_PATH")
DATASET_ID=$(echo "$DATASET_RESULT" | jq -r '.result.structuredContent.rows[0].id // empty')

LOCATION_RESULT=$(send_request "tools/call" '{"name":"execute_sql","arguments":{"query":"SELECT id FROM location WHERE active = true LIMIT 1"}}' "$DB_PATH")
LOCATION_ID=$(echo "$LOCATION_RESULT" | jq -r '.result.structuredContent.rows[0].id // empty')

CLUSTER_RESULT=$(send_request "tools/call" '{"name":"execute_sql","arguments":{"query":"SELECT id FROM cluster WHERE active = true LIMIT 1"}}' "$DB_PATH")
CLUSTER_ID=$(echo "$CLUSTER_RESULT" | jq -r '.result.structuredContent.rows[0].id // empty')

if [ -z "$DATASET_ID" ] || [ -z "$LOCATION_ID" ] || [ -z "$CLUSTER_ID" ]; then
    echo -e "${RED}Error: Could not find test entities in database${NC}"
    exit 1
fi
echo "  Dataset: $DATASET_ID"
echo "  Location: $LOCATION_ID"
echo "  Cluster: $CLUSTER_ID"
echo ""

# === IMPORT_AUDIO_FILES TOOL ===
echo "=== import_audio_files Tool ==="
echo ""

# Test 1: Non-existent folder
echo "Test 1: Non-existent folder (should fail)"
result=$(send_request "tools/call" '{"name":"import_audio_files","arguments":{"folder_path":"/nonexistent/folder","dataset_id":"'"$DATASET_ID"'","location_id":"'"$LOCATION_ID"'","cluster_id":"'"$CLUSTER_ID"'"}}' "$DB_PATH")
run_test "Reject non-existent folder" "false" "$result"

# Test 2: Invalid location ID
echo ""
echo "Test 2: Invalid location_id (should fail)"
result=$(send_request "tools/call" '{"name":"import_audio_files","arguments":{"folder_path":"/tmp","dataset_id":"'"$DATASET_ID"'","location_id":"INVALID123456","cluster_id":"'"$CLUSTER_ID"'"}}' "$DB_PATH")
run_test "Reject invalid location_id" "false" "$result"

echo ""
print_summary

echo ""
echo "Note: These tests validate error handling only."
echo "Actual file import requires real WAV files and valid paths."
echo ""
echo "For bulk import, use the CLI tool:"
echo "  skraak import bulk --db ./db/skraak.duckdb --dataset abc123 --csv import.csv --log progress.log"