"""
Simple unit tests for export service to verify basic functionality
"""

from django.test import TestCase
from django.utils import timezone
from decimal import Decimal
from datetime import date, timedelta
from io import BytesIO
import openpyxl

from reports.export_service import ReportExportService
from loans.models import Loan, LoanProduct, LoanApplication
from users.models import CustomUser


class TestExportServiceBasic(TestCase):
    """Basic tests for export service functionality"""
    
    def setUp(self):
        """Set up test data"""
        # Create test user
        self.user = CustomUser.objects.create_user(
            username='exporttestuser',
            email='exporttest@example.com',
            phone_number='+254700000099',
            first_name='Export',
            last_name='Test'
        )
        
        # Create test loan product
        self.product = LoanProduct.objects.create(
            name='Export 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']
        )
        
        # Create test loan
        self.application = LoanApplication.objects.create(
            borrower=self.user,
            loan_product=self.product,
            requested_amount=Decimal('10000'),
            duration=30,
            repayment_method='monthly',
            status='approved'
        )
        
        self.loan = Loan.objects.create(
            application=self.application,
            borrower=self.user,
            loan_number='LOAN-EXPORT-TEST-001',
            principal_amount=Decimal('10000'),
            interest_amount=Decimal('1000'),
            processing_fee=Decimal('500'),
            total_amount=Decimal('11500'),
            disbursement_date=date(2024, 1, 1),
            due_date=date(2024, 1, 31),
            status='active',
            is_deleted=False,
            is_rolled_over=False
        )
        
        self.export_service = ReportExportService()
    
    def test_format_currency_with_decimal(self):
        """Test currency formatting with Decimal values"""
        result = self.export_service.format_currency(Decimal('10000.50'))
        self.assertEqual(result, 'KES 10,000.50')
    
    def test_format_currency_with_integer(self):
        """Test currency formatting with integer values"""
        result = self.export_service.format_currency(5000)
        self.assertEqual(result, 'KES 5,000.00')
    
    def test_format_currency_with_none(self):
        """Test currency formatting with None"""
        result = self.export_service.format_currency(None)
        self.assertEqual(result, 'KES 0.00')
    
    def test_format_date_with_date_object(self):
        """Test date formatting with date object"""
        test_date = date(2024, 1, 15)
        result = self.export_service.format_date(test_date)
        self.assertEqual(result, '2024-01-15')
    
    def test_format_date_with_none(self):
        """Test date formatting with None"""
        result = self.export_service.format_date(None)
        self.assertEqual(result, 'N/A')
    
    def test_export_to_excel_creates_response(self):
        """Test that Excel export creates a valid HTTP response"""
        report_data = {
            'loans': [{
                'id': self.loan.id,
                'loan_number': self.loan.loan_number,
                'principal_amount': self.loan.principal_amount,
                'disbursement_date': self.loan.disbursement_date
            }]
        }
        
        filters = {}
        
        response = self.export_service.export_to_excel(report_data, 'test_report', filters)
        
        # Check response type
        self.assertEqual(response.status_code, 200)
        
        # Check content type
        self.assertIn('spreadsheet', response['Content-Type'].lower())
        
        # Check Content-Disposition header
        self.assertIn('Content-Disposition', response)
        self.assertIn('attachment', response['Content-Disposition'].lower())
    
    def test_export_to_excel_contains_data(self):
        """Test that Excel export contains the loan data"""
        report_data = {
            'loans': [{
                'id': self.loan.id,
                'loan_number': self.loan.loan_number,
                'principal_amount': self.loan.principal_amount,
                'disbursement_date': self.loan.disbursement_date
            }]
        }
        
        filters = {}
        
        response = self.export_service.export_to_excel(report_data, 'test_report', filters)
        
        # Parse Excel file
        excel_buffer = BytesIO(response.content)
        workbook = openpyxl.load_workbook(excel_buffer)
        sheet = workbook.active
        
        # Check that loan number appears in the sheet
        found_loan_number = False
        for row in sheet.iter_rows(values_only=True):
            if self.loan.loan_number in str(row):
                found_loan_number = True
                break
        
        self.assertTrue(found_loan_number, "Loan number should appear in Excel export")
    
    def test_export_to_pdf_creates_response(self):
        """Test that PDF export creates a valid HTTP response"""
        report_data = {
            'loans': [{
                'id': self.loan.id,
                'loan_number': self.loan.loan_number,
                'principal_amount': self.loan.principal_amount,
                'disbursement_date': self.loan.disbursement_date
            }]
        }
        
        filters = {}
        
        response = self.export_service.export_to_pdf(report_data, 'test_report', filters)
        
        # Check response type
        self.assertEqual(response.status_code, 200)
        
        # Check content type
        self.assertEqual(response['Content-Type'], 'application/pdf')
        
        # Check Content-Disposition header
        self.assertIn('Content-Disposition', response)
        self.assertIn('attachment', response['Content-Disposition'].lower())
    
    def test_export_to_excel_with_filters(self):
        """Test that Excel export includes filter metadata"""
        report_data = {
            'loans': [{
                'id': self.loan.id,
                'loan_number': self.loan.loan_number,
                'principal_amount': self.loan.principal_amount,
                'disbursement_date': self.loan.disbursement_date
            }]
        }
        
        filters = {
            'start_date': date(2024, 1, 1),
            'end_date': date(2024, 1, 31),
            'product_id': str(self.product.id)
        }
        
        response = self.export_service.export_to_excel(report_data, 'test_report', filters)
        
        # Parse Excel file
        excel_buffer = BytesIO(response.content)
        workbook = openpyxl.load_workbook(excel_buffer)
        sheet = workbook.active
        
        # Check that filter info appears in the sheet
        found_filter_info = False
        for row in sheet.iter_rows(values_only=True):
            row_str = ' '.join([str(cell) for cell in row if cell])
            if 'Applied Filters' in row_str or 'Date Range' in row_str:
                found_filter_info = True
                break
        
        self.assertTrue(found_filter_info, "Filter metadata should appear in Excel export")
    
    def test_export_to_excel_with_empty_data(self):
        """Test that Excel export handles empty data gracefully"""
        report_data = {
            'loans': []
        }
        
        filters = {}
        
        response = self.export_service.export_to_excel(report_data, 'test_report', filters)
        
        # Should still create a valid response
        self.assertEqual(response.status_code, 200)
        self.assertIn('spreadsheet', response['Content-Type'].lower())
    
    def test_export_to_pdf_with_empty_data(self):
        """Test that PDF export handles empty data gracefully"""
        report_data = {
            'loans': []
        }
        
        filters = {}
        
        response = self.export_service.export_to_pdf(report_data, 'test_report', filters)
        
        # Should still create a valid response
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/pdf')


if __name__ == '__main__':
    import django
    import os
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
    django.setup()
    
    from django.test.utils import get_runner
    from django.conf import settings
    
    TestRunner = get_runner(settings)
    test_runner = TestRunner()
    failures = test_runner.run_tests(['test_export_service_simple'])
