"""
Fix notification action URLs from old /loans/view/ pattern to new /loans/ pattern
"""
import os
import django

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

from utils.models import Notification

print("=" * 80)
print("FIXING NOTIFICATION ACTION URLs")
print("=" * 80)

# Find all notifications with the old URL pattern
old_pattern = '/loans/view/'
new_pattern = '/loans/'

# Only select the fields we need to avoid foreign key resolution issues
notifications = Notification.objects.filter(action_url__contains=old_pattern).only('id', 'action_url')

count = notifications.count()
print(f"\nFound {count} notifications with old URL pattern")

if count > 0:
    print("\nUpdating URLs...")
    updated = 0
    
    # Use values_list to get just IDs and URLs, avoiding model instantiation issues
    notification_data = Notification.objects.filter(
        action_url__contains=old_pattern
    ).values_list('id', 'action_url')
    
    for notif_id, action_url in notification_data:
        if action_url:
            # Replace the old pattern with the new one
            new_url = action_url.replace(old_pattern, new_pattern)
            Notification.objects.filter(id=notif_id).update(action_url=new_url)
            updated += 1
            
            if updated % 10 == 0:
                print(f"  Updated {updated}/{count}...")
    
    print(f"\n✓ Successfully updated {updated} notifications!")
    print(f"  Old: {old_pattern}<uuid>/")
    print(f"  New: {new_pattern}<uuid>/")
else:
    print("\n✓ No notifications need updating!")

print("\n" + "=" * 80)
print("DONE")
print("=" * 80)
