"""Management command implementing the ApplyDefaultCheckoutForPastDays use case. Intended to be run
once per day, e.g. via cron or Celery beat:

    0 0 * * * /path/to/venv/bin/python manage.py apply_default_checkout

It works organization by organization and skips organizations that are inactive or have the
attendance module disabled (a disabled module must not process anything). See README.md.
"""
from django.core.management.base import BaseCommand

from application.use_cases.attendance import ApplyDefaultCheckoutForPastDays
from apps.modules.services import enabled_module_codes
from apps.organizations.models import Organization
from infrastructure.repositories import DjangoAttendanceRepository


class Command(BaseCommand):
    help = "Apply the default checkout time (17:30) to past days missing a checkout."

    def handle(self, *args, **options):
        total = 0
        for organization in Organization.objects.filter(kind=Organization.Kind.CUSTOMER, is_active=True):
            if "attendance" not in enabled_module_codes(organization):
                continue
            total += ApplyDefaultCheckoutForPastDays(DjangoAttendanceRepository(organization)).execute()
        self.stdout.write(self.style.SUCCESS(f"Applied default checkout to {total} attendance row(s)."))
