from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import OuterRef, Subquery

from apps.calls.models import Notification, Call


class Command(BaseCommand):
    help = "Backfill company for Notification from related Call"

    def handle(self, *args, **options):
        qs = Notification.objects.filter(
            company__isnull=True,
            call__isnull=False
        )

        total = qs.count()
        if total == 0:
            self.stdout.write(self.style.SUCCESS("No Notification to update."))
            return

        self.stdout.write(f"Updating {total} Notification...")

        call_company_subquery = Call.objects.filter(
            id=OuterRef("call_id")
        ).values("company_id")[:1]

        with transaction.atomic():
            updated = qs.update(
                company=Subquery(call_company_subquery)
            )

        self.stdout.write(
            self.style.SUCCESS(f"Successfully updated {updated} Notification.")
        )
