from django.core.management.base import BaseCommand, CommandParser
from django.contrib.auth import get_user_model

class Command(BaseCommand):
	help = "Create a default superuser if no superuser is already present. This aids automatic deployment inside a container."

	def add_arguments(self, parser: CommandParser):
		parser.add_argument('--user',
			help='Username to create if no admin account is present',
			default='admin')
		parser.add_argument('--password',
			help='Password to set for newly created user. Ignored, if any admin user is already present',
			default='admin')

	def handle(self, *args, **options):
		User = get_user_model()

		# Query if there is any admin user
		if not User.objects.filter(is_superuser=True).exists():
			self.stdout.write(f'No superuser present. Creating {options['user']} with supplied password')
			User.objects.create_superuser(username=options['user'], password=options['password'])
		else:
			self.stdout.write('At least one superuser already exists. Skipping superuser creation')