from django.db import migrations, models


def backfill(apps, schema_editor):
    """
    Give every existing install its own prefix.

    The master keeps FT, because every ticket, order and invoice already
    issued carries it and customers have those numbers in their inboxes.
    Everyone else gets letters from their slug. This runs once and never
    touches a row that already has a value.
    """
    import re
    Tenant = apps.get_model('tenants', 'Tenant')
    for t in Tenant.objects.all():
        if t.ref_prefix:
            continue
        if getattr(t, 'is_master', False):
            t.ref_prefix = 'FT'
        else:
            letters = re.sub(r'[^A-Za-z]', '', t.slug or t.name or '')
            t.ref_prefix = (letters[:4].upper() or 'REF')
        t.save(update_fields=['ref_prefix'])


def unbackfill(apps, schema_editor):
    """Reversible on purpose. Clearing the column does not change any
    reference already issued, it only puts the fallback back in charge."""
    Tenant = apps.get_model('tenants', 'Tenant')
    Tenant.objects.update(ref_prefix='')


class Migration(migrations.Migration):
    """
    Per-install reference prefixes.

    'FT-' was hardcoded in five files, and all five are in the template too,
    so every client site would have issued Final Target reference numbers.
    Additive, blank by default, then backfilled in the same migration.
    """

    dependencies = [
        ('tenants', '0021_invoice_payment_link'),
    ]

    operations = [
        migrations.AddField(
            model_name='tenant',
            name='ref_prefix',
            field=models.CharField(blank=True, help_text='Letters in front of ticket and order numbers. Blank uses the slug.', max_length=4),
        ),
        migrations.RunPython(backfill, unbackfill),
    ]
