# Generated by Django 3.0.4 on 2020-12-12 15:00

import django.db.models.deletion
from django.db import migrations, models


def forwards(apps, schema_editor):
    Community = apps.get_model("community", "Community")
    CommunitySite = apps.get_model("community", "CommunitySite")
    Site = apps.get_model("sites", "Site")
    Webhook = apps.get_model("webhooks", "Webhook")
    default_community = Community.objects.filter(identifier="riskofrain2").first()
    if not default_community:
        default_community = Community.objects.create(
            identifier="riskofrain2", name="Risk of Rain 2"
        )
    community_site = default_community.sites.first()
    if not community_site:
        site = Site.objects.filter(community=None).first()
        if not site:
            site = Site.objects.create(
                domain=default_community.identifier, name=default_community.name
            )
        community_site = CommunitySite.objects.create(
            site=site,
            community=default_community,
        )
    for entry in Webhook.objects.all():
        entry.community_site = community_site
        entry.save(update_fields=("community_site",))


class Migration(migrations.Migration):

    dependencies = [
        ("community", "0007_add_community_links"),
        ("webhooks", "0005_add_community_site_relation"),
    ]

    operations = [
        migrations.RunPython(forwards, migrations.RunPython.noop),
        migrations.AlterField(
            model_name="webhook",
            name="community_site",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="webhooks",
                to="community.CommunitySite",
            ),
        ),
    ]
