#!/usr/bin/env python3
"""
Debug the organization switch error.
"""

import json
import urllib.request
import urllib.parse

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

# Login
print("Logging in...")
data = urllib.parse.urlencode({
    'username': EMAIL,
    'password': PASSWORD
}).encode('utf-8')

req = urllib.request.Request(f"{API_BASE}/auth/login", data=data, method='POST')
req.add_header('Content-Type', 'application/x-www-form-urlencoded')

try:
    with urllib.request.urlopen(req) as response:
        response_data = json.loads(response.read().decode('utf-8'))
        token = response_data.get('access_token')
        print(f"Token: {token[:30]}...")
        
        # Try switch with different payload formats
        test_payloads = [
            {"organization_id": 21},
            {"organization_id": "21"},
            {"org_id": 21},
            {"id": 21}
        ]
        
        for payload in test_payloads:
            print(f"\nTrying payload: {payload}")
            data = json.dumps(payload).encode('utf-8')
            req = urllib.request.Request(
                f"{API_BASE}/users/me/active-organization",
                data=data,
                method='PATCH',
                headers={
                    'Authorization': f'Bearer {token}',
                    'Content-Type': 'application/json'
                }
            )
            
            try:
                with urllib.request.urlopen(req) as resp:
                    print(f"Success! Status: {resp.status}")
                    print(f"Response: {resp.read().decode('utf-8')[:200]}")
            except urllib.error.HTTPError as e:
                print(f"HTTP Error {e.code}: {e.reason}")
                print(f"Response: {e.read().decode('utf-8')}")
            except Exception as e:
                print(f"Error: {e}")
                
except Exception as e:
    print(f"Login error: {e}")