#!/usr/bin/env python3
"""
Test script to verify authentication system works correctly
"""

import sys
import os
from pathlib import Path

# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def test_auth_imports():
    """Test that authentication modules can be imported"""
    try:
        from mbetterclient.web_dashboard.auth import AuthManager, AuthenticatedUser
        from mbetterclient.web_dashboard.routes import get_api_auth_decorator
        print("✓ Authentication modules imported successfully")
        return True
    except ImportError as e:
        print(f"✗ Failed to import authentication modules: {e}")
        return False

def test_auth_manager_creation():
    """Test that AuthManager can be created"""
    try:
        from flask import Flask
        from mbetterclient.web_dashboard.auth import AuthManager

        # Create a minimal Flask app for testing
        app = Flask(__name__)
        app.config['SECRET_KEY'] = 'test_secret_key'
        app.config['JWT_SECRET_KEY'] = 'test_jwt_secret'

        # Mock database manager
        class MockDBManager:
            def get_user_by_username(self, username):
                return None
            def get_user_by_id(self, user_id):
                return None

        db_manager = MockDBManager()
        auth_manager = AuthManager(db_manager, app)

        print("✓ AuthManager created successfully")
        return True
    except Exception as e:
        print(f"✗ Failed to create AuthManager: {e}")
        return False

def test_decorator_creation():
    """Test that API auth decorator can be created"""
    try:
        from mbetterclient.web_dashboard.routes import get_api_auth_decorator

        # Test creating decorators
        normal_decorator = get_api_auth_decorator()
        admin_decorator = get_api_auth_decorator(require_admin=True)

        print("✓ API auth decorators created successfully")
        return True
    except Exception as e:
        print(f"✗ Failed to create API auth decorators: {e}")
        return False

def test_authenticated_user_creation():
    """Test that AuthenticatedUser can be created"""
    try:
        from mbetterclient.web_dashboard.auth import AuthenticatedUser

        user = AuthenticatedUser(
            user_id=1,
            username="testuser",
            email="test@example.com",
            is_admin=False,
            role="normal"
        )

        # Test properties
        assert user.id == 1
        assert user.username == "testuser"
        assert user.email == "test@example.com"
        assert user.is_admin == False
        assert user.role == "normal"
        assert user.is_authenticated == True
        assert user.is_active == True
        assert user.is_anonymous == False

        # Test helper methods
        assert user.is_admin_user() == False
        assert user.is_cashier_user() == False
        assert user.is_normal_user() == True

        print("✓ AuthenticatedUser created and tested successfully")
        return True
    except Exception as e:
        print(f"✗ Failed to create/test AuthenticatedUser: {e}")
        return False

def test_role_based_access():
    """Test role-based access control logic"""
    try:
        from mbetterclient.web_dashboard.auth import AuthenticatedUser

        # Test admin user
        admin_user = AuthenticatedUser(
            user_id=1,
            username="admin",
            email="admin@example.com",
            is_admin=True,
            role="admin"
        )

        # Test cashier user
        cashier_user = AuthenticatedUser(
            user_id=2,
            username="cashier",
            email="cashier@example.com",
            is_admin=False,
            role="cashier"
        )

        # Test normal user
        normal_user = AuthenticatedUser(
            user_id=3,
            username="normal",
            email="normal@example.com",
            is_admin=False,
            role="normal"
        )

        # Test admin access
        assert admin_user.is_admin_user() == True
        assert cashier_user.is_admin_user() == False
        assert normal_user.is_admin_user() == False

        # Test cashier access
        assert admin_user.is_cashier_user() == False  # Admin is not cashier
        assert cashier_user.is_cashier_user() == True
        assert normal_user.is_cashier_user() == False

        # Test normal access
        assert admin_user.is_normal_user() == False  # Admin is not normal
        assert cashier_user.is_normal_user() == False  # Cashier is not normal
        assert normal_user.is_normal_user() == True

        print("✓ Role-based access control tested successfully")
        return True
    except Exception as e:
        print(f"✗ Failed to test role-based access control: {e}")
        return False

def main():
    """Run all authentication tests"""
    print("MbetterClient Authentication System Verification")
    print("=" * 50)

    tests = [
        test_auth_imports,
        test_auth_manager_creation,
        test_decorator_creation,
        test_authenticated_user_creation,
        test_role_based_access,
    ]

    passed = 0
    total = len(tests)

    for test in tests:
        try:
            if test():
                passed += 1
            print()
        except Exception as e:
            print(f"✗ Test {test.__name__} failed with exception: {e}")
            print()

    print("=" * 50)
    if passed == total:
        print(f"✓ All {total} authentication tests passed!")
        print("\nThe authentication system appears to be working correctly.")
        print("Key findings:")
        print("- Authentication modules import successfully")
        print("- AuthManager can be instantiated")
        print("- API auth decorators can be created")
        print("- AuthenticatedUser class works correctly")
        print("- Role-based access control logic is correct")
        return True
    else:
        print(f"✗ {total - passed} out of {total} tests failed")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)