#!/bin/bash

# Simple test for organization switching flow
# Uses curl to test the API endpoints

API_BASE="http://localhost:8000"
EMAIL="tester_pro@profibot.hu"
PASSWORD="Password123!"

echo "🧪 Testing Organization Switching Flow"
echo "======================================"

# 1. Login
echo -e "\n1. Logging in as $EMAIL..."
LOGIN_RESPONSE=$(curl -s -X POST "$API_BASE/auth/login" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=$EMAIL&password=$PASSWORD")

ACCESS_TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.access_token // empty')

if [ -z "$ACCESS_TOKEN" ]; then
    echo "❌ Login failed"
    echo "Response: $LOGIN_RESPONSE"
    exit 1
fi

echo "✅ Login successful"
echo "Token: ${ACCESS_TOKEN:0:30}..."

# 2. Get user info
echo -e "\n2. Getting user info..."
USER_INFO=$(curl -s -X GET "$API_BASE/users/me" \
  -H "Authorization: Bearer $ACCESS_TOKEN")

echo "User info:"
echo "$USER_INFO" | jq '{
    id: .id,
    email: .email,
    role: .role,
    scope_id: .scope_id,
    active_organization_id: .active_organization_id,
    person_id: .person_id
}'

# 3. Get organizations
echo -e "\n3. Getting user organizations..."
ORGS=$(curl -s -X GET "$API_BASE/organizations/me" \
  -H "Authorization: Bearer $ACCESS_TOKEN")

ORG_COUNT=$(echo "$ORGS" | jq 'length')
echo "Found $ORG_COUNT organizations:"
echo "$ORGS" | jq '.[] | {id: .id, name: .name, org_type: .org_type}'

# Extract organization IDs
ORG_IDS=$(echo "$ORGS" | jq -r '.[].id')
echo "Organization IDs: $ORG_IDS"

# 4. Test switching to each organization
echo -e "\n4. Testing organization switching..."
for ORG_ID in $ORG_IDS; do
    echo -e "\n🔄 Switching to organization ID: $ORG_ID"
    
    SWITCH_RESPONSE=$(curl -s -X PATCH "$API_BASE/users/me/active-organization" \
      -H "Authorization: Bearer $ACCESS_TOKEN" \
      -H "Content-Type: application/json" \
      -d "{\"organization_id\": $ORG_ID}")
    
    echo "Switch response:"
    echo "$SWITCH_RESPONSE" | jq '.'
    
    # Check if we got a new token
    NEW_TOKEN=$(echo "$SWITCH_RESPONSE" | jq -r '.access_token // empty')
    if [ -n "$NEW_TOKEN" ]; then
        echo "✅ Got new token: ${NEW_TOKEN:0:30}..."
        ACCESS_TOKEN="$NEW_TOKEN"
        
        # Decode token to check scope
        echo "🔍 Decoded token payload:"
        PAYLOAD=$(echo "$NEW_TOKEN" | cut -d'.' -f2 | base64 -d 2>/dev/null || echo "{}")
        echo "$PAYLOAD" | jq '{scope_id: .scope_id, scope_level: .scope_level, role: .role}'
    else
        echo "⚠️ No new token in response"
    fi
    
    # Get updated user info
    echo "📋 Updated user info:"
    UPDATED_INFO=$(curl -s -X GET "$API_BASE/users/me" \
      -H "Authorization: Bearer $ACCESS_TOKEN")
    echo "$UPDATED_INFO" | jq '{scope_id: .scope_id, active_organization_id: .active_organization_id}'
    
    # Get vehicles in current scope
    echo "🚗 Vehicles in current scope:"
    VEHICLES=$(curl -s -X GET "$API_BASE/users/me/assets" \
      -H "Authorization: Bearer $ACCESS_TOKEN")
    VEHICLE_COUNT=$(echo "$VEHICLES" | jq 'length')
    echo "Count: $VEHICLE_COUNT"
    if [ "$VEHICLE_COUNT" -gt 0 ]; then
        echo "$VEHICLES" | jq '.[] | {id: .id, vrm: .vrm, make: .make, model: .model}'
    fi
    
    sleep 1
done

echo -e "\n🎉 Test completed successfully!"
echo "Summary:"
echo "- Login: ✅"
echo "- User info: ✅"
echo "- Organizations: ✅ ($ORG_COUNT found)"
echo "- Organization switching: ✅ (with token refresh)"
echo "- Scope filtering: ✅ (vehicles filtered by organization)"