import psycopg2
import os
from config import ADMIN_CONFIG
import urllib.parse

def test_login_query():
    """Test the exact query used in the login process"""
    try:
        # Parse the DATABASE_URL to extract connection parameters
        parsed = urllib.parse.urlparse(ADMIN_CONFIG['DATABASE_URL'])
        conn = psycopg2.connect(
            host=parsed.hostname,
            port=parsed.port,
            database=parsed.path[1:],  # Remove the leading '/'
            user=parsed.username,
            password=urllib.parse.unquote(parsed.password) if parsed.password else ''
        )
        
        cursor = conn.cursor()
        
        # First, get the user_id for the admin user
        print("=== GETTING USER ID ===")
        cursor.execute("""
            SELECT user_id
            FROM users 
            WHERE email = 'fafakos@qq.com' AND is_active = true
        """)
        user_result = cursor.fetchone()
        
        if not user_result:
            print("❌ User not found")
            return
            
        user_id = user_result[0]
        print(f"User ID: {user_id}")
        
        # Now test the exact query used in auth_routes.py
        print("\n=== TESTING ROLE QUERY ===")
        cursor.execute("""
            SELECT ur.role_name
            FROM users u
            LEFT JOIN user_roles ur ON u.role_id = ur.role_id
            WHERE u.user_id = %s AND ur.role_name IS NOT NULL
        """, (user_id,))
        
        role_result = cursor.fetchone()
        
        if role_result:
            role_name = role_result[0]
            print(f"Role Name: {role_name}")
            
            # Check if user has admin role
            is_admin = role_name.lower() == 'admin'
            print(f"Is Admin: {is_admin}")
            
            if is_admin:
                print("✅ User should see admin menu")
            else:
                print("❌ User should NOT see admin menu")
        else:
            print("❌ No role found for user")
        
        conn.close()
        
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    test_login_query()