import os

from django.core.management.base import BaseCommand, CommandError

from accounts.models import User


class Command(BaseCommand):
    """Sets the admin/agent account passwords from ADMIN_PASSWORD/AGENT_PASSWORD
    in .env, so rotating a password is 'edit .env, rerun this command' — no code
    or database editing involved."""

    help = 'Sync the admin and agent account passwords from environment variables (.env).'

    ACCOUNTS = [
        ('admin', 'ADMIN_PASSWORD', User.Role.ADMIN),
        ('agent', 'AGENT_PASSWORD', User.Role.AGENT),
    ]

    def handle(self, *args, **options):
        for username, env_var, role in self.ACCOUNTS:
            password = os.environ.get(env_var)
            if not password:
                raise CommandError(f'{env_var} is not set in .env')

            user, created = User.objects.get_or_create(
                username=username,
                defaults={'role': role, 'is_staff': role == User.Role.ADMIN, 'is_superuser': role == User.Role.ADMIN},
            )
            user.set_password(password)
            user.save(update_fields=['password'])

            action = 'Created' if created else 'Updated'
            self.stdout.write(self.style.SUCCESS(f'{action} password for {username!r} ({role}).'))
