"""
View to fix loan total amounts through the web interface
"""

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from loans.models import Loan
from decimal import Decimal


@login_required
def fix_loan_totals_view(request):
    """Fix loan total amounts - admin only"""
    
    # Check if user is admin
    if not request.user.is_admin():
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    if request.method == 'POST':
        # Get all loans
        all_loans = Loan.objects.all()
        
        fixed_loans = []
        already_correct = []
        errors = []
        
        for loan in all_loans:
            try:
                # Calculate what the total SHOULD be
                correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
                
                # Check if current total is incorrect
                if loan.total_amount != correct_total:
                    old_total = loan.total_amount
                    difference = correct_total - old_total
                    
                    # Update the loan
                    loan.total_amount = correct_total
                    loan.save()
                    
                    fixed_loans.append({
                        'loan_number': loan.loan_number,
                        'borrower': loan.borrower.get_full_name(),
                        'principal': loan.principal_amount,
                        'interest': loan.interest_amount,
                        'processing_fee': loan.processing_fee,
                        'old_total': old_total,
                        'new_total': correct_total,
                        'difference': difference
                    })
                else:
                    already_correct.append(loan.loan_number)
                    
            except Exception as e:
                errors.append({
                    'loan_number': loan.loan_number,
                    'error': str(e)
                })
        
        if fixed_loans:
            messages.success(request, f'Fixed {len(fixed_loans)} loan(s) successfully!')
        else:
            messages.info(request, 'All loans already have correct totals.')
        
        context = {
            'fixed_loans': fixed_loans,
            'already_correct_count': len(already_correct),
            'errors': errors,
            'total_checked': all_loans.count()
        }
        
        return render(request, 'loans/fix_totals_result.html', context)
    
    # GET request - show confirmation page
    all_loans = Loan.objects.all()
    incorrect_loans = []
    
    for loan in all_loans:
        correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
        if loan.total_amount != correct_total:
            incorrect_loans.append({
                'loan_number': loan.loan_number,
                'borrower': loan.borrower.get_full_name(),
                'principal': loan.principal_amount,
                'interest': loan.interest_amount,
                'processing_fee': loan.processing_fee,
                'current_total': loan.total_amount,
                'correct_total': correct_total,
                'difference': correct_total - loan.total_amount
            })
    
    context = {
        'total_loans': all_loans.count(),
        'incorrect_loans': incorrect_loans,
        'incorrect_count': len(incorrect_loans)
    }
    
    return render(request, 'loans/fix_totals_confirm.html', context)
