from django.utils import timezone
from datetime import date


# ================= DATE RANGE =================
def get_current_month_range():
    today = timezone.now().date()
    start = today.replace(day=1)

    if start.month == 12:
        end = start.replace(year=start.year + 1, month=1, day=1)
    else:
        end = start.replace(month=start.month + 1, day=1)

    return start, end


# ================= OVERDUE MARKING =================
def mark_overdue_invoices():
    from .models import Invoice
    from django.utils import timezone
    from datetime import timedelta

    today = timezone.now().date()

    overdue_invoices = Invoice.objects.filter(
        status__in=["pending", "partial"],
        due_date__lt=today - timedelta(days=3)  # ✅ 3 days grace
    )

    return overdue_invoices.update(status="overdue")


from datetime import timedelta
from django.utils import timezone

def update_invoice_statuses():
    from .models import Invoice

    today = timezone.now().date()

    invoices = Invoice.objects.filter(status__in=["pending", "partial"])

    for inv in invoices:

        if today < inv.due_date:
            inv.status = "pending"

        elif inv.due_date <= today <= inv.due_date + timedelta(days=3):
            inv.status = "due"

        elif today > inv.due_date + timedelta(days=3):
            inv.status = "overdue"

        inv.save(update_fields=["status"])