#!/bin/bash
set -e

BASE_URL="http://solaria:8000/api"
EMAIL="test@normogen.com"
PASSWORD="TestPassword123!"
NEW_PASSWORD="NewPassword456!"

echo "========================================="
echo "Testing Normogen API Endpoints"
echo "========================================="
echo "Base URL: $BASE_URL"
echo ""

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

test_endpoint() {
    local name=$1
    local method=$2
    local endpoint=$3
    local data=$4
    local token=$5
    
    echo -e "${YELLOW}Testing: $name${NC}"
    echo "Request: $method $endpoint"
    
    if [ -z "$token" ]; then
        if [ -z "$data" ]; then
            response=$(curl -s -X $method "$BASE_URL$endpoint" -H "Content-Type: application/json")
        else
            response=$(curl -s -X $method "$BASE_URL$endpoint" -H "Content-Type: application/json" -d "$data")
        fi
    else
        if [ -z "$data" ]; then
            response=$(curl -s -X $method "$BASE_URL$endpoint" -H "Content-Type: application/json" -H "Authorization: Bearer $token")
        else
            response=$(curl -s -X $method "$BASE_URL$endpoint" -H "Content-Type: application/json" -H "Authorization: Bearer $token" -d "$data")
        fi
    fi
    
    echo "Response: $response"
    echo ""
}

echo "========================================="
echo "Phase 1: Health Check (No Auth Required)"
echo "========================================="
test_endpoint "Health Check" "GET" "/../health" "" ""

echo "========================================="
echo "Phase 2: Authentication"
echo "========================================="

# Register a new user
REGISTER_DATA='{"email": "'"$EMAIL"'", "password": "'"$PASSWORD"'", "full_name": "Test User"}'
test_endpoint "Register User" "POST" "/auth/register" "$REGISTER_DATA" ""

# Login
LOGIN_DATA='{"email": "'"$EMAIL"'", "password": "'"$PASSWORD"'"}'
echo -e "${YELLOW}Testing: Login${NC}"
echo "Request: POST /auth/login"
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/auth/login" -H "Content-Type: application/json" -d "$LOGIN_DATA")
echo "Response: $LOGIN_RESPONSE"

# Extract token
ACCESS_TOKEN=$(echo $LOGIN_RESPONSE | jq -r '.access_token // empty')
REFRESH_TOKEN=$(echo $LOGIN_RESPONSE | jq -r '.refresh_token // empty')

if [ -z "$ACCESS_TOKEN" ]; then
    echo -e "${RED}Failed to get access token${NC}"
    exit 1
fi

echo -e "${GREEN}Access Token: ${ACCESS_TOKEN:0:50}...${NC}"
echo ""

echo "========================================="
echo "Phase 3: User Management"
echo "========================================="
test_endpoint "Get Profile" "GET" "/users/me" "" "$ACCESS_TOKEN"

UPDATE_PROFILE_DATA='{"full_name": "Updated Test User"}'
test_endpoint "Update Profile" "PUT" "/users/me" "$UPDATE_PROFILE_DATA" "$ACCESS_TOKEN"

test_endpoint "Get Settings" "GET" "/users/me/settings" "" "$ACCESS_TOKEN"

UPDATE_SETTINGS_DATA='{"theme": "dark"}'
test_endpoint "Update Settings" "PUT" "/users/me/settings" "$UPDATE_SETTINGS_DATA" "$ACCESS_TOKEN"

echo "========================================="
echo "Phase 4: Password Recovery"
echo "========================================="

# Setup recovery phrase first
SET_RECOVERY_DATA='{"email": "'"$EMAIL"'", "recovery_phrase": "my-secret-recovery-phrase"}'
test_endpoint "Set Recovery Phrase" "POST" "/auth/set-recovery-phrase" "$SET_RECOVERY_DATA" ""

# Test password recovery
RECOVER_DATA='{"email": "'"$EMAIL"'", "recovery_phrase": "my-secret-recovery-phrase", "new_password": "'"$NEW_PASSWORD"'"}'
test_endpoint "Recover Password" "POST" "/auth/recover-password" "$RECOVER_DATA" ""

# Login with new password
NEW_LOGIN_DATA='{"email": "'"$EMAIL"'", "password": "'"$NEW_PASSWORD"'"}'
test_endpoint "Login with New Password" "POST" "/auth/login" "$NEW_LOGIN_DATA" ""

# Change password back
CHANGE_PASSWORD_DATA='{"old_password": "'"$NEW_PASSWORD"'", "new_password": "'"$PASSWORD"'"}'
test_endpoint "Change Password" "POST" "/users/me/change-password" "$CHANGE_PASSWORD_DATA" "$ACCESS_TOKEN"

echo "========================================="
echo "Phase 5: Share Management"
echo "========================================="

CREATE_SHARE_DATA='{"target_email": "another@user.com", "resource_type": "profiles", "permissions": ["read"]}'
test_endpoint "Create Share" "POST" "/shares" "$CREATE_SHARE_DATA" "$ACCESS_TOKEN"

test_endpoint "List Shares" "GET" "/shares" "" "$ACCESS_TOKEN"

echo "========================================="
echo "Phase 6: Permissions"
echo "========================================="

CHECK_PERMISSION_DATA='{"resource_id": "507f1f77bcf86cd799439011", "permission": "read"}'
test_endpoint "Check Permission" "POST" "/permissions/check" "$CHECK_PERMISSION_DATA" "$ACCESS_TOKEN"

echo "========================================="
echo "Phase 7: Session Management (NEW)"
echo "========================================="
test_endpoint "Get Sessions" "GET" "/sessions" "" "$ACCESS_TOKEN"

echo "========================================="
echo "All Tests Complete!"
echo "========================================="
