from django.core.management.base import BaseCommand
from django.db.models import Q

from servala.core.models import User


class Command(BaseCommand):
    help = "Make user(s) into staff users"

    def add_arguments(self, parser):
        parser.add_argument(
            "emails",
            nargs="*",
            type=str,
            help="Email addresses of users to make staff",
        )
        parser.add_argument(
            "--substring",
            action="store_true",
            help="Match emails by substring instead of exact match, allowing you to e.g. make all users on your home domain staff users.",
        )

    def handle(self, *args, **options):
        emails = options["emails"]
        substring_match = options["substring"]

        if not emails:
            self.stdout.write(self.style.ERROR("No email addresses provided"))
            return

        query = None
        if substring_match:
            query = Q(email__icontains=emails[0])
            for email in emails:
                query |= Q(email__icontains=email)
        else:
            query = Q(email__in=emails)

        users = User.objects.filter(query)
        already_staff = users.filter(is_staff=True).count()

        if already_staff:
            self.stdout.write(
                self.style.WARNING(
                    f"{already_staff} matching users were already staff users."
                )
            )

        users = users.filter(is_staff=False)
        if not users.exists():
            self.stdout.write(self.style.ERROR("No matching non-staff users found."))
            return

        count = users.count()
        users.update(is_staff=True)
        self.stdout.write(self.style.SUCCESS(f"Made {count} user(s) into staff users"))
