
#!/usr/bin/env python3
"""
Test RateRight Authentication Endpoints
Tests registration and login functionality
"""

import requests
import json
import time
import subprocess
import sys
from threading import Thread

def start_server():
    """Start the Flask server in background"""
    try:
        subprocess.Popen([sys.executable, 'run.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        time.sleep(3)  # Give server time to start
        print("✅ Flask server started")
    except Exception as e:
        print(f"❌ Failed to start server: {e}")

def test_auth_endpoints():
    """Test authentication endpoints"""
    base_url = "http://0.0.0.0:5000"
    
    print("🔧 TESTING RATERIGHT AUTHENTICATION ENDPOINTS")
    print("=" * 60)
    
    # Test health endpoint first
    try:
        response = requests.get(f"{base_url}/api/health", timeout=5)
        print(f"✅ Health check: {response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"❌ Server not responding. Please start with 'python run.py' first")
        return
    
    # Test registration
    print("\n📝 Testing User Registration:")
    registration_data = {
        'email': 'john.smith@example.com',
        'password': 'SecurePass123!',
        'first_name': 'John',
        'last_name': 'Smith', 
        'role': 'contractor',
        'phone_number': '0412345678',
        'location': 'Sydney, NSW',
        'abn_number': '12345678901',
        'business_name': 'Smith Construction Pty Ltd',
        'primary_trade': 'General Building',
        'gst_registered': True
    }
    
    try:
        response = requests.post(f"{base_url}/api/auth/register", 
                               json=registration_data,
                               headers={'Content-Type': 'application/json'})
        
        print(f"   Registration response: {response.status_code}")
        
        if response.status_code == 201:
            data = response.json()
            print(f"   ✅ User registered successfully!")
            print(f"   User ID: {data['user']['id']}")
            print(f"   Email: {data['user']['email']}")
            print(f"   Role: {data['user']['role']}")
            access_token = data['access_token']
            print(f"   ✅ JWT token received")
        else:
            error_data = response.json()
            print(f"   ❌ Registration failed: {error_data.get('error', 'Unknown error')}")
            return
            
    except requests.exceptions.RequestException as e:
        print(f"   ❌ Registration request failed: {e}")
        return
    
    # Test login
    print("\n🔐 Testing User Login:")
    login_data = {
        'email': 'john.smith@example.com',
        'password': 'SecurePass123!'
    }
    
    try:
        response = requests.post(f"{base_url}/api/auth/login",
                               json=login_data,
                               headers={'Content-Type': 'application/json'})
        
        print(f"   Login response: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            print(f"   ✅ Login successful!")
            print(f"   User: {data['user']['first_name']} {data['user']['last_name']}")
            print(f"   Points: {data['user']['total_points']}")
            print(f"   Level: {data['user']['current_level']}")
            access_token = data['access_token']
        else:
            error_data = response.json()
            print(f"   ❌ Login failed: {error_data.get('error', 'Unknown error')}")
            return
            
    except requests.exceptions.RequestException as e:
        print(f"   ❌ Login request failed: {e}")
        return
    
    # Test protected endpoint
    print("\n👤 Testing Protected Endpoint (/api/auth/me):")
    try:
        headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json'
        }
        
        response = requests.get(f"{base_url}/api/auth/me", headers=headers)
        print(f"   Current user response: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            user = data['user']
            print(f"   ✅ Protected endpoint working!")
            print(f"   Business: {user['business_name']}")
            print(f"   ABN: {user['abn_number']}")
            print(f"   GST Registered: {user['gst_registered']}")
            print(f"   Compliance Valid: {user['compliance_valid']}")
            if user['compliance_issues']:
                print(f"   Compliance Issues: {', '.join(user['compliance_issues'])}")
        else:
            error_data = response.json()
            print(f"   ❌ Protected endpoint failed: {error_data.get('error', 'Unknown error')}")
            
    except requests.exceptions.RequestException as e:
        print(f"   ❌ Protected endpoint request failed: {e}")
    
    # Test invalid credentials
    print("\n🚫 Testing Invalid Credentials:")
    invalid_login = {
        'email': 'john.smith@example.com',
        'password': 'WrongPassword'
    }
    
    try:
        response = requests.post(f"{base_url}/api/auth/login",
                               json=invalid_login,
                               headers={'Content-Type': 'application/json'})
        
        print(f"   Invalid login response: {response.status_code}")
        if response.status_code == 401:
            print(f"   ✅ Properly rejected invalid credentials")
        else:
            print(f"   ❌ Should have returned 401 for invalid credentials")
            
    except requests.exceptions.RequestException as e:
        print(f"   ❌ Invalid login test failed: {e}")
    
    print("\n🎉 AUTHENTICATION TESTING COMPLETE!")
    print("=" * 60)
    print("Your RateRight authentication system is working!")

if __name__ == "__main__":
    test_auth_endpoints()
