"""Give every ClientNetwork its own monitor_key.

Added in three steps because the column is UNIQUE: a plain AddField would try to
write the same empty string to every existing row and fail the constraint.
"""
import secrets

from django.db import migrations, models


def gen_keys(apps, schema_editor):
    ClientNetwork = apps.get_model('clients', 'ClientNetwork')
    for net in ClientNetwork.objects.all():
        if not net.monitor_key:
            net.monitor_key = secrets.token_urlsafe(24)[:48]
            net.save(update_fields=['monitor_key'])


class Migration(migrations.Migration):

    dependencies = [
        ('clients', '0012_clientconfiguration_report_emails_and_more'),
    ]

    operations = [
        migrations.AddField(
            model_name='clientnetwork',
            name='monitor_key',
            field=models.CharField(blank=True, default='', max_length=48),
        ),
        migrations.RunPython(gen_keys, migrations.RunPython.noop),
        migrations.AlterField(
            model_name='clientnetwork',
            name='monitor_key',
            field=models.CharField(blank=True, default='', max_length=48, unique=True,
                                   help_text='Auto-generated. Identifies this pfSense to the CRM.'),
        ),
    ]
