"""
Simple unit tests for client report service.

These tests verify the core functionality of the client report service
without using property-based testing.
"""

from django.test import TestCase
from decimal import Decimal
from datetime import timedelta
from django.utils import timezone
import uuid

from loans.models import Loan, LoanProduct, LoanApplication, Repayment
from users.models import CustomUser
from reports.client_report_service import ClientReportService


class TestClientReportServiceBasic(TestCase):
    """Basic unit tests for client report service"""
    
    def setUp(self):
        """Set up test data"""
        self.product = LoanProduct.objects.create(
            name='Test Product',
            product_type='boost',
            description='Test product',
            min_amount=Decimal('1000'),
            max_amount=Decimal('50000'),
            interest_rate=Decimal('10.0'),
            processing_fee=Decimal('5.0'),
            min_duration=7,
            max_duration=90,
            available_repayment_methods=['monthly']
        )
    
    def test_get_client_metrics_excludes_inactive_clients(self):
        """Test that inactive clients are excluded from metrics"""
        # Create active client
        active_client = CustomUser.objects.create_user(
            username='active_test',
            email='active@test.com',
            phone_number='+254700000001',
            first_name='Active',
            last_name='Client',
            role='borrower',
            is_active=True,
            status='active'
        )
        
        # Create inactive client
        inactive_client = CustomUser.objects.create_user(
            username='inactive_test',
            email='inactive@test.com',
            phone_number='+254700000002',
            first_name='Inactive',
            last_name='Client',
            role='borrower',
            is_active=False,
            status='inactive'
        )
        
        # Get metrics
        metrics = ClientReportService.get_client_metrics()
        
        # Should only count active client
        self.assertEqual(metrics['total_clients'], 1)
        
        # Cleanup
        active_client.delete()
        inactive_client.delete()
    
    def test_calculate_client_score_returns_zero_for_no_loans(self):
        """Test that clients with no loans get score of 0"""
        client = CustomUser.objects.create_user(
            username='no_loans_test',
            email='noloans@test.com',
            phone_number='+254700000003',
            first_name='No',
            last_name='Loans',
            role='borrower',
            is_active=True,
            status='active'
        )
        
        score = ClientReportService.calculate_client_score(client)
        
        self.assertEqual(score, 0.0)
        
        # Cleanup
        client.delete()
    
    def test_calculate_repayment_rate_basic(self):
        """Test basic repayment rate calculation"""
        client = CustomUser.objects.create_user(
            username='repayment_test',
            email='repayment@test.com',
            phone_number='+254700000004',
            first_name='Repayment',
            last_name='Test',
            role='borrower',
            is_active=True,
            status='active'
        )
        
        # Create loan with 50% repayment
        app = LoanApplication.objects.create(
            application_number=f'APP-{uuid.uuid4().hex[:6]}',
            borrower=client,
            loan_product=self.product,
            requested_amount=Decimal('10000'),
            requested_duration=30,
            purpose='Test',
            status='approved'
        )
        
        loan = Loan.objects.create(
            loan_number=f'LOAN-{uuid.uuid4().hex[:6]}',
            application=app,
            borrower=client,
            principal_amount=Decimal('10000'),
            interest_amount=Decimal('1000'),
            processing_fee=Decimal('500'),
            total_amount=Decimal('11500'),
            amount_paid=Decimal('5750'),  # 50%
            disbursement_date=timezone.now(),
            due_date=timezone.now() + timedelta(days=30),
            duration_days=30,
            status='active'
        )
        
        rate = ClientReportService.calculate_repayment_rate(client)
        
        self.assertAlmostEqual(rate, 50.0, places=1)
        
        # Cleanup
        loan.delete()
        app.delete()
        client.delete()
    
    def test_get_performance_distribution_categories(self):
        """Test that performance distribution uses correct thresholds"""
        # Verify thresholds are set correctly
        self.assertEqual(ClientReportService.EXCELLENT_THRESHOLD, 85)
        self.assertEqual(ClientReportService.GOOD_THRESHOLD, 70)
        self.assertEqual(ClientReportService.AVERAGE_THRESHOLD, 50)
    
    def test_get_top_performers_limits_to_10(self):
        """Test that top performers returns at most 10 clients"""
        # Create 15 clients
        clients = []
        for i in range(15):
            client = CustomUser.objects.create_user(
                username=f'top_test_{i}',
                email=f'top{i}@test.com',
                phone_number=f'+25470{1000000 + i}',
                first_name=f'Top{i}',
                last_name='Test',
                role='borrower',
                is_active=True,
                status='active'
            )
            clients.append(client)
        
        # Get top performers
        top_performers = ClientReportService.get_top_performers(limit=10)
        
        # Should return at most 10
        self.assertLessEqual(len(top_performers), 10)
        
        # Cleanup
        for client in clients:
            client.delete()
    
    def test_get_top_performers_ordered_by_repayment_rate(self):
        """Test that top performers are ordered by repayment rate"""
        # Create 3 clients with different repayment rates
        clients = []
        for i in range(3):
            client = CustomUser.objects.create_user(
                username=f'order_test_{i}',
                email=f'order{i}@test.com',
                phone_number=f'+25470{2000000 + i}',
                first_name=f'Order{i}',
                last_name='Test',
                role='borrower',
                is_active=True,
                status='active'
            )
            
            # Create loan with different repayment rates (90%, 50%, 70%)
            repayment_rates = [90, 50, 70]
            app = LoanApplication.objects.create(
                application_number=f'APP-ORDER-{uuid.uuid4().hex[:6]}',
                borrower=client,
                loan_product=self.product,
                requested_amount=Decimal('10000'),
                requested_duration=30,
                purpose='Test',
                status='approved'
            )
            
            total = Decimal('11500')
            paid = total * Decimal(str(repayment_rates[i] / 100))
            
            loan = Loan.objects.create(
                loan_number=f'LOAN-ORDER-{uuid.uuid4().hex[:6]}',
                application=app,
                borrower=client,
                principal_amount=Decimal('10000'),
                interest_amount=Decimal('1000'),
                processing_fee=Decimal('500'),
                total_amount=total,
                amount_paid=paid,
                disbursement_date=timezone.now(),
                due_date=timezone.now() + timedelta(days=30),
                duration_days=30,
                status='active'
            )
            
            clients.append(client)
        
        # Get top performers
        top_performers = ClientReportService.get_top_performers(limit=10)
        
        # Should be ordered: 90%, 70%, 50%
        self.assertGreaterEqual(top_performers[0]['repayment_rate'], 
                               top_performers[1]['repayment_rate'])
        self.assertGreaterEqual(top_performers[1]['repayment_rate'], 
                               top_performers[2]['repayment_rate'])
        
        # Cleanup
        Loan.objects.all().delete()
        LoanApplication.objects.all().delete()
        for client in clients:
            client.delete()


print("Client report service tests created successfully")
