#!/usr/bin/env python3
"""
Test script to verify branch filtering is working correctly for utils pages:
- /utils/receipts/
- /utils/notifications/
- /utils/documents/
"""

import os
import sys
import django
from django.conf import settings

# Add the project root to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
from utils.models import Receipt, Notification, Document, DocumentTag
from loans.models import Loan, Repayment
from users.models import Branch

User = get_user_model()

def test_branch_filtering():
    """Test branch filtering for utils pages"""
    
    print("🔍 Testing Branch Filtering for Utils Pages")
    print("=" * 50)
    
    # Create test branches
    branch1 = Branch.objects.create(name="Branch 1", code="BR001")
    branch2 = Branch.objects.create(name="Branch 2", code="BR002")
    
    # Create test users
    superuser = User.objects.create_user(
        username='superuser',
        email='super@test.com',
        password='testpass123',
        is_superuser=True,
        is_staff=True
    )
    
    branch1_user = User.objects.create_user(
        username='branch1user',
        email='branch1@test.com',
        password='testpass123',
        branch=branch1
    )
    
    branch2_user = User.objects.create_user(
        username='branch2user',
        email='branch2@test.com',
        password='testpass123',
        branch=branch2
    )
    
    staff_user = User.objects.create_user(
        username='staffuser',
        email='staff@test.com',
        password='testpass123',
        is_staff=True
    )
    
    print(f"✅ Created test users and branches")
    
    # Create test data
    # Create notifications for different branches
    notif1 = Notification.objects.create(
        user=branch1_user,
        title="Branch 1 Notification",
        message="Test notification for branch 1",
        notification_type="system_maintenance"
    )
    
    notif2 = Notification.objects.create(
        user=branch2_user,
        title="Branch 2 Notification", 
        message="Test notification for branch 2",
        notification_type="system_maintenance"
    )
    
    # System notification (no user)
    system_notif = Notification.objects.create(
        user=None,
        title="System Notification",
        message="System-wide notification",
        notification_type="system_maintenance"
    )
    
    # Create documents for different branches
    doc1 = Document.objects.create(
        name="Branch 1 Document",
        uploaded_by=branch1_user,
        document_type="other"
    )
    
    doc2 = Document.objects.create(
        name="Branch 2 Document",
        uploaded_by=branch2_user,
        document_type="other"
    )
    
    public_doc = Document.objects.create(
        name="Public Document",
        uploaded_by=branch1_user,
        document_type="other",
        is_public=True
    )
    
    print(f"✅ Created test notifications and documents")
    
    # Test client
    client = Client()
    
    # Test 1: Superuser without branch selection (should see all)
    print("\n📋 Test 1: Superuser without branch selection")
    client.login(username='superuser', password='testpass123')
    
    # Test notifications
    response = client.get('/utils/notifications/')
    if response.status_code == 200:
        print("✅ Notifications page accessible")
        # Should see all notifications
        content = response.content.decode()
        if "Branch 1 Notification" in content and "Branch 2 Notification" in content:
            print("✅ Superuser sees all branch notifications")
        else:
            print("❌ Superuser not seeing all notifications")
    else:
        print(f"❌ Notifications page error: {response.status_code}")
    
    # Test documents
    response = client.get('/utils/documents/')
    if response.status_code == 200:
        print("✅ Documents page accessible")
        # Should see all documents
        content = response.content.decode()
        if "Branch 1 Document" in content and "Branch 2 Document" in content:
            print("✅ Superuser sees all branch documents")
        else:
            print("❌ Superuser not seeing all documents")
    else:
        print(f"❌ Documents page error: {response.status_code}")
    
    # Test receipts
    response = client.get('/utils/receipts/')
    if response.status_code == 200:
        print("✅ Receipts page accessible")
    else:
        print(f"❌ Receipts page error: {response.status_code}")
    
    client.logout()
    
    # Test 2: Branch user (should see only their branch)
    print("\n📋 Test 2: Branch 1 user")
    client.login(username='branch1user', password='testpass123')
    
    # Test notifications
    response = client.get('/utils/notifications/')
    if response.status_code == 200:
        print("✅ Notifications page accessible")
        content = response.content.decode()
        if "Branch 1 Notification" in content and "System Notification" in content:
            print("✅ Branch user sees own branch + system notifications")
            if "Branch 2 Notification" not in content:
                print("✅ Branch user doesn't see other branch notifications")
            else:
                print("❌ Branch user seeing other branch notifications")
        else:
            print("❌ Branch user not seeing correct notifications")
    else:
        print(f"❌ Notifications page error: {response.status_code}")
    
    # Test documents
    response = client.get('/utils/documents/')
    if response.status_code == 200:
        print("✅ Documents page accessible")
        content = response.content.decode()
        if "Branch 1 Document" in content and "Public Document" in content:
            print("✅ Branch user sees own branch + public documents")
            if "Branch 2 Document" not in content:
                print("✅ Branch user doesn't see other branch private documents")
            else:
                print("❌ Branch user seeing other branch private documents")
        else:
            print("❌ Branch user not seeing correct documents")
    else:
        print(f"❌ Documents page error: {response.status_code}")
    
    client.logout()
    
    # Test 3: Superuser with branch selection
    print("\n📋 Test 3: Superuser with branch selection")
    client.login(username='superuser', password='testpass123')
    
    # Set branch in session
    session = client.session
    session['selected_branch_id'] = branch1.id
    session.save()
    
    # Test notifications
    response = client.get('/utils/notifications/')
    if response.status_code == 200:
        print("✅ Notifications page accessible with branch filter")
        content = response.content.decode()
        if "Branch 1 Notification" in content and "System Notification" in content:
            print("✅ Superuser with branch filter sees selected branch + system notifications")
            if "Branch 2 Notification" not in content:
                print("✅ Superuser with branch filter doesn't see other branch notifications")
            else:
                print("❌ Superuser with branch filter seeing other branch notifications")
        else:
            print("❌ Superuser with branch filter not seeing correct notifications")
    else:
        print(f"❌ Notifications page error: {response.status_code}")
    
    client.logout()
    
    print("\n🎉 Branch filtering tests completed!")
    print("=" * 50)
    
    # Cleanup
    try:
        # Delete test data
        Notification.objects.filter(title__contains="Branch").delete()
        Notification.objects.filter(title="System Notification").delete()
        Document.objects.filter(name__contains="Branch").delete()
        Document.objects.filter(name="Public Document").delete()
        User.objects.filter(username__in=['superuser', 'branch1user', 'branch2user', 'staffuser']).delete()
        Branch.objects.filter(code__in=['BR001', 'BR002']).delete()
        print("✅ Cleanup completed")
    except Exception as e:
        print(f"⚠️ Cleanup warning: {e}")

if __name__ == '__main__':
    test_branch_filtering()