# Generated by Django 5.2 on 2025-06-18 21:01

from django.db import migrations


def populate_decodo_ip_ports(apps, schema_editor):
    """
    Populate port numbers for existing DecodoIP records.
    Assigns sequential port numbers starting from each block's start_port.
    """
    DecodoIP = apps.get_model('api', 'DecodoIP')
    DecodoIPBlock = apps.get_model('api', 'DecodoIPBlock')
    
    # Process each IP block
    for ip_block in DecodoIPBlock.objects.all():
        # Get all DecodoIP records for this block, ordered by creation time
        ips_in_block = DecodoIP.objects.filter(ip_block=ip_block).order_by('created_at')
        
        # Assign sequential port numbers starting from the block's start_port
        for index, decodo_ip in enumerate(ips_in_block):
            decodo_ip.port = ip_block.start_port + index
            decodo_ip.save(update_fields=['port'])
            
        print(f"Updated {ips_in_block.count()} IPs for block {ip_block.endpoint}:{ip_block.start_port}")


def reverse_populate_decodo_ip_ports(apps, schema_editor):
    """
    Reverse migration - reset all port values to 0
    """
    DecodoIP = apps.get_model('api', 'DecodoIP')
    DecodoIP.objects.all().update(port=0)


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0029_decodoip_port_decodoip_api_decodoi_port_4bb967_idx_and_more'),
    ]

    operations = [
        migrations.RunPython(
            populate_decodo_ip_ports,
            reverse_populate_decodo_ip_ports
        ),
    ]
