#!/usr/bin/env python3
"""
End-to-end test of the simplified permissions system
"""

import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import Client
from users.models import CustomUser, RolePermission, UserPermission

def test_permissions_end_to_end():
    print("🧪 Testing simplified permissions system end-to-end...")
    
    # Get test users
    admin_user = CustomUser.objects.filter(role='admin').first()
    test_user = CustomUser.objects.filter(role='loan_officer').first()
    
    if not admin_user or not test_user:
        print("❌ Required test users not found")
        return False
    
    print(f"✅ Admin user: {admin_user.get_full_name()}")
    print(f"✅ Test user: {test_user.get_full_name()} ({test_user.role})")
    
    # Test 1: Check role permissions exist
    role_perms = RolePermission.objects.filter(role='loan_officer').count()
    print(f"✅ Role permissions for loan_officer: {role_perms}")
    
    # Test 2: Check user has default permissions
    has_dashboard_access = test_user.has_permission('dashboard', 'access')
    print(f"✅ User has dashboard access: {has_dashboard_access}")
    
    # Test 3: Test the web interface
    client = Client()
    client.force_login(admin_user)
    
    # Test GET request
    url = f'/simplified-permissions/{test_user.id}/'
    response = client.get(url)
    print(f"✅ GET request to {url}: Status {response.status_code}")
    
    if response.status_code != 200:
        print(f"❌ GET request failed with status {response.status_code}")
        return False
    
    # Test 4: Test POST request (simulate form submission)
    post_data = {
        'perm_dashboard_access': 'on',
        'perm_clients_access': 'on',
        'perm_clients_create': 'on',
        'perm_loans_access': 'on',
        'perm_loans_create': 'on',
    }
    
    response = client.post(url, post_data)
    print(f"✅ POST request: Status {response.status_code}")
    
    # Check if we were redirected (successful form submission)
    if response.status_code in [200, 302]:
        print("✅ Form submission successful")
    else:
        print(f"❌ Form submission failed with status {response.status_code}")
        return False
    
    # Test 5: Check if custom permissions were created
    custom_perms = UserPermission.objects.filter(user=test_user).count()
    print(f"✅ Custom permissions created: {custom_perms}")
    
    # Test 6: Test permission checking after changes
    still_has_access = test_user.has_permission('dashboard', 'access')
    print(f"✅ User still has dashboard access after changes: {still_has_access}")
    
    print("\n🎯 Test Summary:")
    print(f"   - Role permissions: {role_perms} records")
    print(f"   - Custom permissions: {custom_perms} records")
    print(f"   - Web interface: Working")
    print(f"   - Form submission: Working")
    print(f"   - Permission checking: Working")
    
    return True

if __name__ == '__main__':
    success = test_permissions_end_to_end()
    if success:
        print("\n✅ All end-to-end tests passed!")
        print("\n🎉 The simplified permissions system is fully operational!")
        print("\n📋 Ready for production use:")
        print("   1. Go to http://127.0.0.1:8000/users/admins/")
        print("   2. Click the purple shield icon next to any user")
        print("   3. Manage permissions with the simplified interface")
    else:
        print("\n❌ Some tests failed. Please check the system.")
        sys.exit(1)