#!/bin/bash
# Script to test API endpoints with authentication

echo "========================================="
echo "Mobile API Test with Authentication"
echo "========================================="
echo ""

# Get base URL
BASE_URL=$(grep APP_URL .env 2>/dev/null | cut -d '=' -f2 | tr -d '"' | tr -d "'" | tr -d ' ')
if [ -z "$BASE_URL" ]; then
    BASE_URL="https://portal.afrilen.com"
fi

API_URL="${BASE_URL}/api/v1"

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Get credentials
echo "Enter login credentials:"
read -p "Email/Student ID: " LOGIN
read -sp "Password: " PASSWORD
echo ""
read -p "Role (student/instructor/admin) [student]: " ROLE
ROLE=${ROLE:-student}

echo ""
echo "Logging in..."

# Login
LOGIN_RESPONSE=$(curl -s -X POST "${API_URL}/auth/login" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d "{\"login\":\"${LOGIN}\",\"password\":\"${PASSWORD}\",\"role\":\"${ROLE}\"}")

# Extract token
TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"token":"[^"]*' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
    echo -e "${RED}✗ Login failed!${NC}"
    echo "Response: $LOGIN_RESPONSE"
    exit 1
fi

echo -e "${GREEN}✓ Login successful!${NC}"
echo "Token: ${TOKEN:0:20}..."
echo ""

# Test endpoints with token
echo "========================================="
echo "Testing Protected Endpoints"
echo "========================================="
echo ""

test_endpoint() {
    local endpoint=$1
    local description=$2
    
    echo -n "Testing: $description ... "
    
    response=$(curl -s -w "\n%{http_code}" -X GET "${API_URL}${endpoint}" \
      -H "Content-Type: application/json" \
      -H "Accept: application/json" \
      -H "Authorization: Bearer ${TOKEN}")
    
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')
    
    if [ "$http_code" = "200" ]; then
        echo -e "${GREEN}✓ PASS${NC} (HTTP $http_code)"
        # Show first 100 chars of response
        echo "  Response preview: $(echo "$body" | head -c 100)..."
        return 0
    else
        echo -e "${RED}✗ FAIL${NC} (HTTP $http_code)"
        echo "  Response: $(echo "$body" | head -c 200)"
        return 1
    fi
}

# Test various endpoints
test_endpoint "/student/dashboard" "Dashboard"
test_endpoint "/student/books" "Books List"
test_endpoint "/student/quizzes" "Quizzes List"
test_endpoint "/student/courses" "Courses List"
test_endpoint "/student/videos" "Videos List"
test_endpoint "/student/certificates" "Certificates List"
test_endpoint "/notifications" "Notifications"
test_endpoint "/notifications/unread-count" "Unread Count"
test_endpoint "/auth/user" "Current User"

echo ""
echo "========================================="
echo "Test Complete!"
echo "========================================="

