"""Terms & Agreement resolution and publishing (V2 §2.2 direction).

Mirrors payments.fees's effective-dated-schedule pattern: exactly one
AgreementTemplate should be "active" at a time, and publishing a new version
supersedes the previous one rather than leaving multiple active rows.
"""

from django.db.models import Q
from django.utils import timezone

from .models import AgreementTemplate


def active_agreement(at=None):
	"""The Terms & Agreement version currently in force, or None if none
	has ever been published."""
	at = at or timezone.now()
	return (
		AgreementTemplate.objects.filter(is_active=True, effective_from__lte=at)
		.filter(Q(effective_to__isnull=True) | Q(effective_to__gte=at))
		.order_by("-version")
		.first()
	)


def publish_agreement(title: str, body: str, *, created_by: str = "") -> AgreementTemplate:
	"""Publish a new version, closing out whatever was previously active."""
	now = timezone.now()
	last = AgreementTemplate.objects.order_by("-version").first()
	next_version = (last.version + 1) if last else 1

	AgreementTemplate.objects.filter(is_active=True).update(is_active=False, effective_to=now)

	return AgreementTemplate.objects.create(
		title=title,
		body=body,
		version=next_version,
		is_active=True,
		effective_from=now,
		created_by=created_by[:120],
	)
