#!/bin/bash
# Security audit script - run to verify security implementation

echo "=== Security Audit ==="
echo ""

BASE_URL="${1:-http://localhost:3000}"

echo "1. Testing unauthenticated API access (should fail)..."
echo "   Testing /api/children..."
curl -s "$BASE_URL/api/children" | grep -q "error" && echo "   ✓ PASS - Blocked" || echo "   ✗ FAIL - Should return error"

echo ""
echo "2. Testing unauthenticated growth access (should fail)..."
curl -s "$BASE_URL/api/growth?childId=test" | grep -q "error" && echo "   ✓ PASS - Blocked" || echo "   ✗ FAIL - Should return error"

echo ""
echo "3. Testing unauthenticated logs access (should fail)..."
curl -s "$BASE_URL/api/logs?childId=test&type=feed" | grep -q "error" && echo "   ✓ PASS - Blocked" || echo "   ✗ FAIL - Should return error"

echo ""
echo "4. Testing vaccinations access (should fail)..."
curl -s "$BASE_URL/api/vaccinations?childId=test" | grep -q "error" && echo "   ✓ PASS - Blocked" || echo "   ✗ FAIL - Should return error"

echo ""
echo "5. Testing medicines access (should fail)..."
curl -s "$BASE_URL/api/medicines?childId=test" | grep -q "error" && echo "   ✓ PASS - Blocked" || echo "   ✗ FAIL - Should return error"

echo ""
echo "6. Testing session cookie setting..."
RESPONSE=$(curl -s -c /tmp/cookies.txt -X POST "$BASE_URL/api/auth/signin" \
  -H "Content-Type: application/json" \
  -d '{"email":"test@test.com","password":"wrong"}')
echo "   Response: $RESPONSE"

echo ""
echo "7. Testing rate limiting..."
for i in 1 2 3 4 5 6; do
  curl -s "$BASE_URL/api/auth/signin" \
    -H "Content-Type: application/json" \
    -d '{"email":"hacker@test.com","password":"guess"}' | grep -q "Too many" && break
done
echo "   Rate limited after $i attempts"

echo ""
echo "=== Audit Complete ==="