from datetime import datetime
from django.db import transaction
from .models import GlobalCounter, Reference

GLOBAL_SCOPE = "global"


def peek_next_index() -> int:
    """
    Return the next index number WITHOUT incrementing/saving.
    Used for the preview page.
    """
    try:
        counter = GlobalCounter.objects.get(scope_key=GLOBAL_SCOPE)
        return counter.next_index
    except GlobalCounter.DoesNotExist:
        return 1


@transaction.atomic
def issue_reference(*, user, sector_code: str, title: str, status: str, at: datetime | None = None) -> Reference:
    """
    Atomically increments the counter and creates a Reference row.
    """
    now = at or datetime.now()
    counter, created = GlobalCounter.objects.select_for_update().get_or_create(
        scope_key=GLOBAL_SCOPE,
        defaults={"next_index": 1},
    )

    index = counter.next_index
    counter.next_index = index + 1
    counter.save(update_fields=["next_index"])

    ref = Reference.objects.create(
        index=index,
        sector=sector_code,
        day=now.day,
        month=now.month,
        year=now.year,
        title=title,
        status=status,
        assigned_to=user,
    )
    return ref