"""Recovery helper functions."""

from datetime import datetime

from django.urls import reverse
from django.utils.text import slugify
from django.utils.timezone import now

from authentik.core.models import Group, Token, TokenIntents, User


def create_admin_group(user: User) -> Group:
    """Create admin group and add user to it."""
    group, _ = Group.objects.update_or_create(
        name="authentik Admins",
        defaults={
            "is_superuser": True,
        },
    )
    group.users.add(user)

    return group


def create_recovery_token(user: User, expiry: datetime, generated_from: str) -> tuple[Token, str]:
    """Create recovery token and associated link"""
    _now = now()
    token = Token.objects.create(
        expires=expiry,
        user=user,
        intent=TokenIntents.INTENT_RECOVERY,
        description=f"Recovery Token generated by {generated_from} on {_now}",
        identifier=slugify(f"ak-recovery-{user}-{_now}"),
    )
    url = reverse("authentik_recovery:use-token", kwargs={"key": str(token.key)})
    return token, url
