#!/usr/bin/env python
"""
Test script for Registration Fees Management System
"""
import os
import sys
import django
from decimal import Decimal

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

from django.contrib.auth import get_user_model
from reports.enhanced_models import RegistrationFee, RegistrationFeePayment
from reports.forms import RegistrationFeeForm, RegistrationFeePaymentForm

User = get_user_model()

def test_registration_fees_system():
    """Test the registration fees management system"""
    print("Testing Registration Fees Management System...")
    print("=" * 50)
    
    # Test 1: Create a registration fee
    print("\n1. Testing Registration Fee Creation...")
    try:
        from django.utils import timezone
        
        fee_data = {
            'product_type': 'boost',
            'fee_name': 'Boost Registration Fee',
            'amount': Decimal('500.00'),
            'description': 'Registration fee for Boost product',
            'is_active': True,
            'effective_from': timezone.now()
        }
        
        form = RegistrationFeeForm(data=fee_data)
        if form.is_valid():
            fee = form.save(commit=False)
            # Get or create a test user for created_by
            import uuid
            unique_id = str(uuid.uuid4())[:8]
            test_user, created = User.objects.get_or_create(
                username='test_admin',
                defaults={
                    'first_name': 'Test',
                    'last_name': 'Admin',
                    'email': f'test{unique_id}@example.com',
                    'phone_number': f'+254700{unique_id[:6]}',
                    'role': 'admin'
                }
            )
            fee.created_by = test_user
            fee.save()
            print(f"✓ Registration fee created successfully: {fee.fee_name}")
            print(f"  - ID: {fee.id}")
            print(f"  - Amount: KES {fee.amount}")
            print(f"  - Product Type: {fee.get_product_type_display()}")
        else:
            print(f"✗ Form validation failed: {form.errors}")
            return False
    except Exception as e:
        print(f"✗ Error creating registration fee: {e}")
        return False
    
    # Test 2: Test fee queries
    print("\n2. Testing Registration Fee Queries...")
    try:
        active_fees = RegistrationFee.objects.active()
        print(f"✓ Active fees count: {active_fees.count()}")
        
        boost_fees = RegistrationFee.objects.by_product_type('boost')
        print(f"✓ Boost product fees count: {boost_fees.count()}")
        
        effective_fees = RegistrationFee.objects.effective_now()
        print(f"✓ Currently effective fees count: {effective_fees.count()}")
    except Exception as e:
        print(f"✗ Error querying registration fees: {e}")
        return False
    
    # Test 3: Create a test customer and payment
    print("\n3. Testing Registration Fee Payment...")
    try:
        # Get or create a test customer
        import uuid
        unique_id = str(uuid.uuid4())[:8]
        test_customer, created = User.objects.get_or_create(
            username='test_customer',
            defaults={
                'first_name': 'Test',
                'last_name': 'Customer',
                'email': f'customer{unique_id}@example.com',
                'phone_number': f'+254701{unique_id[:6]}',
                'role': 'borrower'
            }
        )
        
        # Create a payment
        from django.utils import timezone
        payment_data = {
            'customer': test_customer.id,
            'registration_fee': fee.id,
            'amount_paid': Decimal('500.00'),
            'payment_method': 'mpesa',
            'payment_date': timezone.now(),
            'transaction_reference': 'TEST123456',
            'payment_notes': 'Test payment for registration fee'
        }
        
        form = RegistrationFeePaymentForm(data=payment_data)
        if form.is_valid():
            payment = form.save(commit=False)
            payment.processed_by = test_user
            payment.save()
            print(f"✓ Registration fee payment recorded successfully")
            print(f"  - Receipt Number: {payment.receipt_number}")
            print(f"  - Customer: {payment.customer.get_full_name()}")
            print(f"  - Amount: KES {payment.amount_paid}")
            print(f"  - Payment Method: {payment.get_payment_method_display()}")
        else:
            print(f"✗ Payment form validation failed: {form.errors}")
            return False
    except Exception as e:
        print(f"✗ Error creating registration fee payment: {e}")
        return False
    
    # Test 4: Test payment analytics
    print("\n4. Testing Payment Analytics...")
    try:
        analytics = RegistrationFeePayment.objects.get_revenue_analytics()
        print(f"✓ Revenue analytics generated successfully:")
        print(f"  - Total Revenue: KES {analytics['total_revenue']}")
        print(f"  - Total Payments: {analytics['total_payments']}")
        print(f"  - Average Payment: KES {analytics['avg_payment']}")
        
        if analytics['revenue_by_product']:
            print("  - Revenue by Product:")
            for product in analytics['revenue_by_product']:
                print(f"    * {product['registration_fee__product_type']}: KES {product['total']}")
        
        if analytics['revenue_by_method']:
            print("  - Revenue by Payment Method:")
            for method in analytics['revenue_by_method']:
                print(f"    * {method['payment_method']}: KES {method['total']}")
    except Exception as e:
        print(f"✗ Error generating payment analytics: {e}")
        return False
    
    # Test 5: Test comprehensive reports service
    print("\n5. Testing Comprehensive Reports Service...")
    try:
        from reports.comprehensive_reports import reports_service
        
        report_data = reports_service.get_registration_fees_report()
        print(f"✓ Registration fees report generated successfully:")
        print(f"  - Report Type: {report_data['report_type']}")
        print(f"  - Total Income: KES {report_data['summary']['total_registration_income']}")
        print(f"  - Total Registrations: {report_data['summary']['total_registrations']}")
        print(f"  - Average Fee: KES {report_data['summary']['average_registration_fee']}")
    except Exception as e:
        print(f"✗ Error generating comprehensive report: {e}")
        return False
    
    print("\n" + "=" * 50)
    print("✓ All tests passed! Registration Fees Management System is working correctly.")
    return True

if __name__ == '__main__':
    success = test_registration_fees_system()
    sys.exit(0 if success else 1)