#!/bin/bash

# Start server in background
echo "Starting server..."
cd backend
./server &
SERVER_PID=$!

# Wait for server to start
sleep 2

# Test API endpoints
echo ""
echo "Testing API endpoints..."
echo ""

# Test 1: List files (should be empty initially)
echo "1. Testing GET /api/files"
curl -s http://127.0.0.1:8080/api/files
echo ""
echo ""

# Test 2: Create a file
echo "2. Testing POST /api/files"
curl -s -X POST http://127.0.0.1:8080/api/files \
  -H "Content-Type: application/json" \
  -d '{"name":"test.md","content":"# Test Heading\n\nTest content."}'
echo ""
echo ""

# Test 3: List files (should have one file)
echo "3. Testing GET /api/files"
curl -s http://127.0.0.1:8080/api/files
echo ""
echo ""

# Test 4: Get a file
echo "4. Testing GET /api/files/test.md"
curl -s http://127.0.0.1:8080/api/files/test.md
echo ""
echo ""

# Test 5: Update a file
echo "5. Testing PUT /api/files/test.md"
curl -s -X PUT http://127.0.0.1:8080/api/files/test.md \
  -H "Content-Type: application/json" \
  -d '{"content":"# Updated Heading\n\nUpdated content."}'
echo ""
echo ""

# Test 6: List files (should still have one file)
echo "6. Testing GET /api/files"
curl -s http://127.0.0.1:8080/api/files
echo ""
echo ""

# Test 7: Delete a file
echo "7. Testing DELETE /api/files/test.md"
curl -s -X DELETE http://127.0.0.1:8080/api/files/test.md
echo ""
echo ""

# Test 8: List files (should be empty again)
echo "8. Testing GET /api/files"
curl -s http://127.0.0.1:8080/api/files
echo ""
echo ""

# Cleanup
echo "Stopping server..."
kill $SERVER_PID
wait $SERVER_PID 2>/dev/null

echo "API test completed successfully!"
