"""Celery tasks for the job board (relocated out of the retired REP LMS)."""
from __future__ import annotations

import logging

from celery import shared_task
from django.utils import timezone

logger = logging.getLogger(__name__)


@shared_task
def expire_job_listings() -> None:
    """Deactivate job listings past ``closes_at`` (PRD SP8).

    Flips both ``is_active=False`` and ``listing_status=EXPIRED`` on a single
    pass so the two columns stay in lock-step. Only PUBLISHED rows are flipped —
    DRAFT / PENDING / REJECTED retain their lifecycle status.
    """
    from apps.alumni.careers.models import JobListing

    today = timezone.now().date()
    n = JobListing.objects.filter(
        is_active=True,
        closes_at__lt=today,
        listing_status=JobListing.ListingStatus.PUBLISHED,
    ).update(
        is_active=False,
        listing_status=JobListing.ListingStatus.EXPIRED,
    )
    if n:
        logger.info("careers.expire_job_listings updated=%s", n)


@shared_task
def retry_pending_alumni_handoffs() -> int:
    """Periodic re-attempt of FAILED Alumni handoff rows (FRREP-TS007).

    Wired in ``config/celery.py`` beat schedule (hourly). No-op when
    ``ALUMNI_WEBHOOK_URL`` is unset.
    """
    from apps.alumni.careers.handoffs import retry_failed_alumni_handoffs

    return retry_failed_alumni_handoffs()
