from django.db import migrations


def seed_accounting_role(apps, schema_editor):
    Role = apps.get_model("core", "Role")
    Permission = apps.get_model("core", "Permission")

    accounting, _ = Role.objects.get_or_create(
        slug="accounting-staff",
        defaults={
            "name": "Accounting Staff",
            "description": "Maintains journals, ledgers, controls, and statutory reports.",
            "is_system": True,
        },
    )
    manager = Role.objects.filter(slug="fat-manager").first()
    for action in ("view", "create", "update"):
        permission, _ = Permission.objects.get_or_create(
            domain="accounting",
            action=action,
            defaults={"label": f"Accounting {action.title()}"},
        )
        accounting.permissions.add(permission)
        if manager:
            manager.permissions.add(permission)

    approve, _ = Permission.objects.get_or_create(
        domain="accounting",
        action="approve",
        defaults={"label": "Accounting Approve"},
    )
    if manager:
        manager.permissions.add(approve)


class Migration(migrations.Migration):
    dependencies = [("core", "0009_finance_roles")]
    operations = [migrations.RunPython(seed_accounting_role, migrations.RunPython.noop)]
