#!/bin/bash

echo "Starting backend service..."
docker compose up -d db backend

echo "Waiting for backend to start..."
sleep 5

echo "Testing API health endpoint..."
curl -s http://localhost:4000/health | jq

echo "Fetching product categories..."
curl -s http://localhost:4000/api/products/categories/all | jq

echo "Fetching all products..."
curl -s http://localhost:4000/api/products | jq

echo "Fetching Rock category products..."
curl -s http://localhost:4000/api/products/category/Rock | jq

echo "Testing user registration..."
curl -s -X POST http://localhost:4000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com","firstName":"Test","lastName":"User"}' | jq

echo "Testing login request..."
curl -s -X POST http://localhost:4000/api/auth/login-request \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com"}' | jq

# Save the auth code for the next step
AUTH_CODE=$(curl -s -X POST http://localhost:4000/api/auth/login-request \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com"}' | jq -r '.code')

echo "Testing login verification with code: $AUTH_CODE"
RESPONSE=$(curl -s -X POST http://localhost:4000/api/auth/verify \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"test@example.com\",\"code\":\"$AUTH_CODE\"}")

echo $RESPONSE | jq

USER_ID=$(echo $RESPONSE | jq -r '.userId')
API_KEY=$(echo $RESPONSE | jq -r '.token')

echo "User ID: $USER_ID"
echo "API Key: $API_KEY"

echo "Verifying API key..."
curl -s -X POST http://localhost:4000/api/auth/verify-key \
  -H "Content-Type: application/json" \
  -d "{\"apiKey\":\"$API_KEY\"}" | jq

echo "Testing cart for user: $USER_ID with API key"
curl -s http://localhost:4000/api/cart/$USER_ID \
  -H "X-API-Key: $API_KEY" | jq

echo "Adding a product to the cart..."
PRODUCT_ID=$(curl -s http://localhost:4000/api/products | jq -r '.[0].id')
curl -s -X POST http://localhost:4000/api/cart/add \
  -H "Content-Type: application/json" \
  -d "{\"userId\":\"$USER_ID\",\"productId\":\"$PRODUCT_ID\",\"quantity\":1}" | jq

echo "Showing updated cart..."
curl -s http://localhost:4000/api/cart/$USER_ID | jq

echo "Test complete!"