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

from gaehsnitz.models import User


class Command(BaseCommand):
    help = "Merge source user into target user, then delete source"

    def add_arguments(self, parser):
        parser.add_argument("source", help="Username of user to merge FROM (will be deleted)")
        parser.add_argument("target", help="Username of user to merge INTO (will be kept)")

    def handle(self, *args, **options):
        source_name = options["source"]
        target_name = options["target"]

        if source_name == target_name:
            raise CommandError("Source and target must be different users")

        try:
            source = User.objects.get(username=source_name)
        except User.DoesNotExist:
            raise CommandError(f"Source user '{source_name}' not found")

        try:
            target = User.objects.get(username=target_name)
        except User.DoesNotExist:
            raise CommandError(f"Target user '{target_name}' not found")

        with transaction.atomic():
            payments = source.user_payments.count()
            consumptions = source.consumption_list.count()

            source.user_payments.update(user=target)
            source.consumption_list.update(user=target)

            source.delete()

        self.stdout.write(
            self.style.SUCCESS(
                f"Merged '{source_name}' into '{target_name}': "
                f"{payments} payment(s), {consumptions} consumption(s) reassigned. "
                f"Source user deleted."
            )
        )
