from django.core.management.base import BaseCommand

from billing.workflows import create_renewal_for_service
from services.models import Service


class Command(BaseCommand):
    help = "Cria renovações para serviços recorrentes com data definida, sem duplicar registos existentes."

    def add_arguments(self, parser):
        parser.add_argument("--service", type=int, help="ID de um serviço específico.")

    def handle(self, *args, **options):
        queryset = Service.objects.filter(is_recurring=True, next_renewal_date__isnull=False)
        if options.get("service"):
            queryset = queryset.filter(pk=options["service"])

        created = 0
        existing = 0
        errors = 0
        for service in queryset.select_related("client"):
            try:
                _, was_created = create_renewal_for_service(service)
                created += int(was_created)
                existing += int(not was_created)
            except ValueError as exc:
                errors += 1
                self.stderr.write(f"{service}: {exc}")

        self.stdout.write(self.style.SUCCESS(f"Renovações criadas: {created}; já existentes: {existing}; erros: {errors}."))
