import time

import jwt
from django.conf import settings


def generate_massmail_token(
    massmail_uuid: str, recipient_email: str | None = None, secret: str = None, expires_in_hours: int = 24 * 7
) -> str:
    """
    Encodes massmail UUID and recipient email into a JWT token for secure email tracking or webview.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    payload = {
        "uuid": str(massmail_uuid),
        "exp": time.time() + (expires_in_hours * 3600),  # Unix timestamp
        "iat": time.time(),
    }
    if recipient_email:
        payload["email"] = recipient_email
    token = jwt.encode(payload, secret, algorithm="HS256")
    return token
