# Generated by Django 3.2.19 on 2024-09-19 08:29

from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.exceptions import IrreversibleError
from django.db.migrations.state import StateApps

from debusine.db.models.scopes import FALLBACK_SCOPE_NAME


def set_fallback_scope(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    """Set all scopeless workspaces to the fallback scope."""
    Scope = apps.get_model("db", "Scope")
    Workspace = apps.get_model("db", "Workspace")
    fallback_scope = Scope.objects.get(name=FALLBACK_SCOPE_NAME)
    Workspace.objects.filter(scope__isnull=True).update(scope=fallback_scope)


def revert_fallback_scope(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    Workspace = apps.get_model("db", "Workspace")
    if Workspace.objects.exclude(
        models.Q(scope__isnull=True) | models.Q(scope__name=FALLBACK_SCOPE_NAME)
    ).exists():
        raise IrreversibleError(
            "non-fallback scopes are in use: can't revert to scopeless workspaces"
        )


class Migration(migrations.Migration):
    dependencies = [
        ('db', '0082_workspace_add_scope'),
    ]

    operations = [
        migrations.RunPython(set_fallback_scope, revert_fallback_scope)
    ]
