from django.core.management.base import BaseCommand
from django.utils import timezone

from staff.employment import StaffEmploymentService
from staff.models import ClubStaffAssignment


class Command(BaseCommand):
    help = (
        "End expired NPC staff assignments and materialize earned salary obligations."
    )

    def handle(self, *args, **options):
        count = 0
        rows = ClubStaffAssignment.objects.filter(
            status="ACTIVE", staff_member__source_type="NPC"
        ).select_related("staff_member")
        for row in rows.iterator():
            plans = row.staff_member.payroll_plans.filter(club_id=row.club_id)
            if (
                plans.exists()
                and not plans.filter(
                    end_date__gte=timezone.localdate(), status__in=["ACTIVE", "ENDED"]
                ).exists()
            ):
                StaffEmploymentService.end(assignment_id=row.pk)
                count += 1
        self.stdout.write(f"Ended {count} expired staff assignments.")
