"""
Test delinquent loans report filtering for rolled-over and deleted loans.

This test verifies that the delinquent loans report properly excludes:
- Rolled-over loans (status='rolled_over' or is_rolled_over=True)
- Soft-deleted loans (is_deleted=True)

Requirements: 4.4, 5.3
"""

import os
import django

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

from django.test import TestCase, RequestFactory
from django.contrib.auth import get_user_model
from django.utils import timezone
from datetime import timedelta
from decimal import Decimal

from loans.models import Loan
from reports.views import enhanced_delinquent_loans_report
from reports.filter_service import ReportFilterService
from reports.calculation_service import LoanCalculationService

User = get_user_model()


def test_delinquent_loans_exclude_rolled_over_and_deleted():
    """
    Test that delinquent loans report excludes rolled-over and soft-deleted loans.
    
    Validates: Requirements 4.4, 5.3
    """
    print("\n" + "="*80)
    print("TEST: Delinquent Loans Report - Exclude Rolled-Over and Deleted Loans")
    print("="*80)
    
    # Get all loans that are overdue
    today = timezone.now().date()
    overdue_loans = Loan.objects.filter(due_date__lt=timezone.now())
    
    print(f"\n📊 Total overdue loans in database: {overdue_loans.count()}")
    
    # Count loans by status
    active_overdue = overdue_loans.filter(is_deleted=False, is_rolled_over=False).exclude(status='rolled_over')
    rolled_over_overdue = overdue_loans.filter(is_rolled_over=True) | overdue_loans.filter(status='rolled_over')
    deleted_overdue = overdue_loans.filter(is_deleted=True)
    
    print(f"   - Active overdue loans: {active_overdue.count()}")
    print(f"   - Rolled-over overdue loans: {rolled_over_overdue.count()}")
    print(f"   - Soft-deleted overdue loans: {deleted_overdue.count()}")
    
    # Apply filter service
    print("\n🔍 Applying ReportFilterService.apply_loan_status_filter()...")
    filtered_loans = ReportFilterService.apply_loan_status_filter(
        overdue_loans,
        exclude_rolled_over=True,
        exclude_deleted=True
    )
    
    print(f"   Filtered loans count: {filtered_loans.count()}")
    
    # Verify no rolled-over loans in results
    rolled_over_in_results = filtered_loans.filter(
        is_rolled_over=True
    ).count() + filtered_loans.filter(status='rolled_over').count()
    
    print(f"\n✅ Verification Results:")
    print(f"   - Rolled-over loans in filtered results: {rolled_over_in_results}")
    
    if rolled_over_in_results == 0:
        print(f"   ✅ PASS: No rolled-over loans in results")
    else:
        print(f"   ❌ FAIL: Found {rolled_over_in_results} rolled-over loans in results")
    
    # Verify no deleted loans in results
    deleted_in_results = filtered_loans.filter(is_deleted=True).count()
    print(f"   - Soft-deleted loans in filtered results: {deleted_in_results}")
    
    if deleted_in_results == 0:
        print(f"   ✅ PASS: No soft-deleted loans in results")
    else:
        print(f"   ❌ FAIL: Found {deleted_in_results} soft-deleted loans in results")
    
    # Verify calculations use LoanCalculationService
    print(f"\n🧮 Testing LoanCalculationService calculations...")
    
    if filtered_loans.exists():
        sample_loan = filtered_loans.first()
        print(f"   Sample loan: {sample_loan.loan_number or f'LOAN-{sample_loan.id}'}")
        
        # Test calculations
        days_overdue = LoanCalculationService.calculate_days_overdue(sample_loan)
        outstanding = LoanCalculationService.calculate_outstanding_amount(sample_loan)
        amount_paid = LoanCalculationService.calculate_amount_paid(sample_loan)
        
        print(f"   - Days overdue: {days_overdue}")
        print(f"   - Outstanding amount: {LoanCalculationService.format_currency(outstanding)}")
        print(f"   - Amount paid: {LoanCalculationService.format_currency(amount_paid)}")
        print(f"   ✅ LoanCalculationService methods working correctly")
    else:
        print(f"   ℹ️  No active delinquent loans to test calculations")
    
    # Summary
    print(f"\n" + "="*80)
    print("SUMMARY")
    print("="*80)
    
    all_passed = rolled_over_in_results == 0 and deleted_in_results == 0
    
    if all_passed:
        print("✅ ALL TESTS PASSED")
        print("   - Rolled-over loans are properly excluded")
        print("   - Soft-deleted loans are properly excluded")
        print("   - LoanCalculationService is being used for calculations")
    else:
        print("❌ SOME TESTS FAILED")
        if rolled_over_in_results > 0:
            print(f"   - {rolled_over_in_results} rolled-over loans found in results")
        if deleted_in_results > 0:
            print(f"   - {deleted_in_results} soft-deleted loans found in results")
    
    print("="*80 + "\n")
    
    return all_passed


if __name__ == '__main__':
    test_delinquent_loans_exclude_rolled_over_and_deleted()
