#!/bin/bash
#
# Test script for CopyMeThat import functionality
# Usage: ./scripts/test-import.sh
#

set -e

BASE_URL="http://localhost:3000"
EXPORT_HTML="data/exports/Copy_Me_That_HTML_20260328_58775_z1p5lpjsgz/recipes.html"
EXPORT_TXT_DIR="data/exports/Copy_Me_That_TXT_20260328_58775_z1p5lpjsgz"

echo "🧪 Testing CopyMeThat Import Functionality"
echo "=========================================="
echo ""

# Check if server is running
if ! curl -s "$BASE_URL" > /dev/null; then
  echo "❌ Error: Backend server is not running at $BASE_URL"
  echo "   Start it with: npm run dev"
  exit 1
fi

echo "✅ Server is running"
echo ""

# Test 1: Import from HTML file
echo "📝 Test 1: Import from HTML file"
echo "--------------------------------"

if [ ! -f "$EXPORT_HTML" ]; then
  echo "❌ HTML export file not found: $EXPORT_HTML"
  exit 1
fi

echo "Uploading: $EXPORT_HTML"
RESPONSE=$(curl -s -X POST "$BASE_URL/api/import/local" \
  -F "files=@$EXPORT_HTML" \
  -F "skipDuplicates=true")

echo "Response:"
echo "$RESPONSE" | jq '.'

IMPORTED=$(echo "$RESPONSE" | jq '.data.imported')
SKIPPED=$(echo "$RESPONSE" | jq '.data.skipped')
FAILED=$(echo "$RESPONSE" | jq '.data.failed')

echo ""
echo "📊 Results:"
echo "  Imported: $IMPORTED"
echo "  Skipped:  $SKIPPED"
echo "  Failed:   $FAILED"
echo ""

if [ "$IMPORTED" -gt 0 ]; then
  echo "✅ HTML import successful!"
else
  echo "⚠️  Warning: No recipes imported from HTML"
fi

echo ""
echo "---"
echo ""

# Test 2: Import from TXT files (sample of 3 files)
echo "📝 Test 2: Import from TXT files (sample)"
echo "----------------------------------------"

if [ ! -d "$EXPORT_TXT_DIR" ]; then
  echo "❌ TXT export directory not found: $EXPORT_TXT_DIR"
  exit 1
fi

# Get first 3 .txt files
TXT_FILES=$(find "$EXPORT_TXT_DIR" -name "*.txt" | head -3)

if [ -z "$TXT_FILES" ]; then
  echo "❌ No .txt files found in: $EXPORT_TXT_DIR"
  exit 1
fi

echo "Uploading 3 sample TXT files..."

# Build curl command with multiple -F flags
CURL_CMD="curl -s -X POST \"$BASE_URL/api/import/local\" -F \"skipDuplicates=true\""

for file in $TXT_FILES; do
  CURL_CMD="$CURL_CMD -F \"files=@$file\""
done

RESPONSE=$(eval $CURL_CMD)

echo "Response:"
echo "$RESPONSE" | jq '.'

IMPORTED=$(echo "$RESPONSE" | jq '.data.imported')
SKIPPED=$(echo "$RESPONSE" | jq '.data.skipped')
FAILED=$(echo "$RESPONSE" | jq '.data.failed')

echo ""
echo "📊 Results:"
echo "  Imported: $IMPORTED"
echo "  Skipped:  $SKIPPED"
echo "  Failed:   $FAILED"
echo ""

if [ "$IMPORTED" -gt 0 ] || [ "$SKIPPED" -gt 0 ]; then
  echo "✅ TXT import successful!"
else
  echo "⚠️  Warning: No recipes imported from TXT files"
fi

echo ""
echo "=========================================="
echo "🎉 Import tests complete!"
echo ""
echo "To view imported recipes:"
echo "  curl $BASE_URL/api/recipes | jq '.data.recipes[] | {id, title, made, rating}'"
