"""Password reset email: product branding and EmailLog auditability."""

import pytest
from django.test import Client, override_settings

from apps.core.models import User
from apps.notifications.models import EmailLog


@pytest.fixture
def user(db):
    return User.objects.create_user(email="reset@x.test", password="pw12345!")


RESET_SETTINGS = dict(
    EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
    PRODUCT_NAME="Nocthink",
)


@pytest.mark.django_db
class TestPasswordResetEmail:
    @override_settings(**RESET_SETTINGS)
    def test_writes_emaillog_row(self, user):
        """Without a log row, "I never got the link" is unanswerable — and the
        enumeration-safe 200 hides send failures from the caller."""
        Client().post(
            "/api/auth/password-reset/",
            {"email": user.email},
            content_type="application/json",
        )
        row = EmailLog.objects.filter(recipient_email=user.email).first()
        assert row is not None
        assert row.status == "sent"
        assert row.notification_type == "password_reset"

    @override_settings(**RESET_SETTINGS)
    def test_subject_uses_configured_product_name(self, user):
        from django.core import mail

        Client().post(
            "/api/auth/password-reset/",
            {"email": user.email},
            content_type="application/json",
        )
        assert len(mail.outbox) == 1
        assert mail.outbox[0].subject == "Reset your Nocthink password"
        assert "K-Hub" not in mail.outbox[0].subject

    @override_settings(**RESET_SETTINGS)
    def test_unknown_email_sends_nothing_but_still_200(self):
        from django.core import mail

        res = Client().post(
            "/api/auth/password-reset/",
            {"email": "nobody@x.test"},
            content_type="application/json",
        )
        assert res.status_code == 200
        assert len(mail.outbox) == 0
        assert EmailLog.objects.count() == 0


@pytest.mark.django_db
@override_settings(
    EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
    PRODUCT_NAME="Nocthink",
)
def test_activation_email_uses_product_name():
    from django.core import mail

    from apps.core.activation import send_activation_email

    u = User.objects.create_user(email="activate@x.test", password="pw12345!")
    send_activation_email(u)
    assert mail.outbox[0].subject == "Activate your Nocthink account"
    assert "Welcome to Nocthink" in mail.outbox[0].body
    assert "K-Hub" not in mail.outbox[0].body


def test_product_name_defaults_to_caridu_branding():
    """caridu shipped as K-Hub before this setting existed; that must not change."""
    from django.conf import settings

    assert settings.PRODUCT_NAME == "K-Hub"
