#!/bin/bash

echo "=========================================="
echo "Testing Authentication Setup"
echo "=========================================="
echo ""

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

# Base URL
BASE_URL="http://localhost:8000/api"

echo -e "${YELLOW}Step 1: Testing Login Endpoint${NC}"
echo "POST $BASE_URL/auth/login"
echo ""

# Test login with sample credentials
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/auth/login" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "ten_dang_nhap": "admin",
    "mat_khau": "password123"
  }')

echo "Response:"
echo "$LOGIN_RESPONSE" | jq '.' 2>/dev/null || echo "$LOGIN_RESPONSE"
echo ""

# Extract token from response
TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.data.token' 2>/dev/null)

if [ "$TOKEN" != "null" ] && [ ! -z "$TOKEN" ]; then
    echo -e "${GREEN}✓ Login successful! Token received.${NC}"
    echo ""
    
    echo -e "${YELLOW}Step 2: Testing Get User Endpoint${NC}"
    echo "GET $BASE_URL/auth/user"
    echo ""
    
    # Test get user with token
    USER_RESPONSE=$(curl -s -X GET "$BASE_URL/auth/user" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Accept: application/json")
    
    echo "Response:"
    echo "$USER_RESPONSE" | jq '.' 2>/dev/null || echo "$USER_RESPONSE"
    echo ""
    
    if echo "$USER_RESPONSE" | jq -e '.success' > /dev/null 2>&1; then
        echo -e "${GREEN}✓ Get user successful!${NC}"
        echo ""
        
        echo -e "${YELLOW}Step 3: Testing Logout Endpoint${NC}"
        echo "POST $BASE_URL/auth/logout"
        echo ""
        
        # Test logout
        LOGOUT_RESPONSE=$(curl -s -X POST "$BASE_URL/auth/logout" \
          -H "Authorization: Bearer $TOKEN" \
          -H "Accept: application/json")
        
        echo "Response:"
        echo "$LOGOUT_RESPONSE" | jq '.' 2>/dev/null || echo "$LOGOUT_RESPONSE"
        echo ""
        
        if echo "$LOGOUT_RESPONSE" | jq -e '.success' > /dev/null 2>&1; then
            echo -e "${GREEN}✓ Logout successful!${NC}"
        else
            echo -e "${RED}✗ Logout failed!${NC}"
        fi
    else
        echo -e "${RED}✗ Get user failed!${NC}"
    fi
else
    echo -e "${RED}✗ Login failed! Please check:${NC}"
    echo "  1. Server is running (php artisan serve)"
    echo "  2. Database is configured correctly"
    echo "  3. Migration has been run (php artisan migrate)"
    echo "  4. Test user exists in database"
    echo "  5. Passport is installed (php artisan passport:install)"
fi

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