from datetime import datetime

from celery.app import shared_task
from constance import config
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.utils.translation import activate
from django.utils.translation import gettext_lazy as _

from core.utils import get_dynamic_email_connection
from payments.models import Transaction


@shared_task(queue="default")
def balance_deposit_email(transaction_pk: str) -> tuple[bool, str]:
    try:
        transaction = Transaction.objects.get(pk=transaction_pk)
    except Transaction.DoesNotExist:
        return False, f"Transaction not found with the given pk: {transaction_pk}"

    if not transaction.balance or not transaction.balance.user:
        return False, f"Balance not found for the given transaction pk: {transaction_pk}"

    activate(transaction.balance.user.language)

    email = EmailMessage(
        _(f"{config.PROJECT_NAME} | balance deposit"),
        render_to_string(
            template_name="balance_deposit_email.html",
            context={
                "amount": transaction.amount,
                "balance": transaction.balance.amount,
                "user_first_name": transaction.balance.user.first_name,
                "project_name": config.PROJECT_NAME,
                "contact_email": config.EMAIL_FROM,
                "today": datetime.today(),
            },
        ),
        to=[transaction.balance.user.email],
        from_email=f"{config.PROJECT_NAME} <{config.EMAIL_FROM}>",
        connection=get_dynamic_email_connection(),
    )
    email.content_subtype = "html"
    email.send()

    return True, str(transaction_pk)
