"""
Undo the footer links seeded by 0012 and 0013.

Those two are data migrations that write Final Target's own footer, FT Panel,
FT Ads, FT BizHub and a finaltarget.com link, into whatever database runs them.
Every install got them, which is why a brand new client site came up wearing
Final Target's footer.

The seeds are history and are not edited. This corrects the result instead.

Two cases, because the same code runs on the master and on a tenant:

  A tenant row already exists, so this is an established install. The orphan
  rows are attached to it. They become that site's own links, editable in its
  panel, and nothing disappears from a live footer.

  No tenant row exists, so this is a fresh install part way through
  provisioning. The rows are deleted and the site starts with an empty footer,
  which is the correct blank state.
"""
from django.db import migrations


def rehome_or_remove(apps, schema_editor):
    FooterLink = apps.get_model('pages', 'FooterLink')
    Tenant = apps.get_model('tenants', 'Tenant')

    orphans = FooterLink.objects.filter(tenant__isnull=True)
    if not orphans.exists():
        return

    owner = Tenant.objects.filter(is_master=True).first() or Tenant.objects.first()
    if owner is None:
        orphans.delete()
    else:
        orphans.update(tenant=owner)


def noop(apps, schema_editor):
    """Nothing to undo. Recreating another company's footer is not a fix."""


class Migration(migrations.Migration):

    dependencies = [
        ('pages', '0033_null_site_defaults'),
        ('tenants', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(rehome_or_remove, noop),
    ]
