from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from apps.access.models import MembershipRole, Role
from apps.audit import services as audit
from apps.organizations.models import Organization, OrganizationMembership


class Command(BaseCommand):
    help = (
        "Appoint an existing account as NoTeam platform super admin. Deliberately explicit: no "
        "migration ever grants platform-wide power implicitly. Run bootstrap_core first."
    )

    def add_arguments(self, parser):
        parser.add_argument("--username", required=True)

    @transaction.atomic
    def handle(self, *args, **opts):
        User = get_user_model()
        user = User.objects.filter(username__iexact=opts["username"]).first()
        if user is None:
            raise CommandError("No account with that username.")
        platform = Organization.objects.filter(kind=Organization.Kind.PLATFORM).first()
        role = Role.objects.filter(organization=platform, code="super_admin").first() if platform else None
        if role is None:
            raise CommandError("Run `manage.py bootstrap_core` first.")

        membership, _ = OrganizationMembership.objects.get_or_create(user=user, organization=platform)
        membership.status = OrganizationMembership.Status.ACTIVE
        membership.save(update_fields=["status"])
        MembershipRole.objects.get_or_create(membership=membership, role=role)
        audit.record(
            actor=None, action="platform.super_admin_granted", organization=platform,
            entity_type="membership", entity_id=membership.pk, after={"user_id": user.pk, "username": user.username},
        )
        self.stdout.write(self.style.SUCCESS(f"'{user.username}' is now platform super admin."))
