from django.core.exceptions import ValidationError
from django.db import transaction
from apps.document_engine.models import CancelledDocumentNumber, DocumentRecord, DocumentSequence


@transaction.atomic
def allocate_document_number(
    *,
    company,
    document_type,
    branch=None,
    fiscal_year=None,
    phase: str = DocumentSequence.Phase.FINAL,
    manual_number: str = "",
) -> str:
    """Atomically generate duplicate-safe document numbers scoped per company/branch/FY/phase."""
    seq, _ = DocumentSequence.objects.select_for_update().get_or_create(
        company=company,
        branch=branch,
        fiscal_year=fiscal_year,
        document_type=document_type,
        phase=phase,
        defaults={
            "prefix": (
                f"DRF-{document_type.default_prefix}-"
                if phase == DocumentSequence.Phase.DRAFT
                else f"{document_type.default_prefix}-"
            ),
            "digit_length": 5,
            "last_number": 0,
        },
    )

    if manual_number:
        if not seq.allow_manual_override:
            raise ValidationError("Manual document number override is disabled for this sequence.")
        candidate = manual_number.strip()
        if CancelledDocumentNumber.objects.filter(
            company=company, document_type=document_type, document_number=candidate
        ).exists():
            raise ValidationError(f"Cancelled document number '{candidate}' cannot be reused.")
        if DocumentRecord.objects.filter(
            company=company, document_type=document_type, document_number=candidate
        ).exists():
            raise ValidationError(f"Document number '{candidate}' already exists.")
        return candidate

    while True:
        seq.last_number += 1
        candidate = seq.format_number(seq.last_number)
        cancelled = CancelledDocumentNumber.objects.filter(
            company=company, document_type=document_type, document_number=candidate
        ).exists()
        duplicate = DocumentRecord.objects.filter(
            company=company, document_type=document_type, document_number=candidate
        ).exists()
        if not cancelled and not duplicate:
            seq.save(update_fields=["last_number", "updated_at"])
            return candidate


@transaction.atomic
def cancel_document_number(*, company, document_type, document_number: str, user, reason: str) -> CancelledDocumentNumber:
    obj, _ = CancelledDocumentNumber.objects.get_or_create(
        company=company,
        document_type=document_type,
        document_number=document_number,
        defaults={"reason": reason, "cancelled_by": user},
    )
    return obj

