#!/usr/bin/env python
"""
Create test duplicate repayments to verify the deletion script works correctly.
"""
import os
import django
from decimal import Decimal
from datetime import timedelta

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

from django.utils import timezone
from loans.models import Loan, Repayment
from utils.models import Receipt

def create_test_duplicates():
    """Create some test duplicate repayments"""
    print("\n" + "="*80)
    print("CREATING TEST DUPLICATE REPAYMENTS")
    print("="*80)
    
    # Find an active loan
    loan = Loan.objects.filter(status='active').first()
    
    if not loan:
        print("✗ No active loans found")
        return False
    
    print(f"\n✓ Using loan: {loan.loan_number}")
    print(f"  Borrower: {loan.borrower.get_full_name()}")
    
    # Count existing repayments
    existing_count = Repayment.objects.filter(loan=loan).count()
    print(f"\n  Existing repayments: {existing_count}")
    
    # Create 3 duplicate repayments (same amount, same time)
    print(f"\n  Creating 3 duplicate repayments...")
    
    base_time = timezone.now()
    test_amount = Decimal('500.00')
    
    created_ids = []
    for i in range(3):
        # Create with slightly different times (within 1 second)
        payment_time = base_time + timedelta(milliseconds=i*100)
        
        rep = Repayment.objects.create(
            loan=loan,
            amount=test_amount,
            payment_method='cash',
            payment_date=payment_time
        )
        created_ids.append(rep.id)
        print(f"    ✓ Created repayment ID {rep.id} - {rep.receipt_number}")
    
    # Verify they were created
    new_count = Repayment.objects.filter(loan=loan).count()
    print(f"\n  Total repayments now: {new_count}")
    print(f"  Created {new_count - existing_count} duplicates")
    
    print("\n✓ Test duplicates created successfully!")
    print(f"  IDs: {created_ids}")
    
    return True

if __name__ == '__main__':
    create_test_duplicates()
