from __future__ import annotations

import pytest

pytest.importorskip("websockets")

import pipelet_ocpp_broker as broker


def test_disconnect_alert_mail_settings_fall_back_to_config(monkeypatch):
    for key in [
        "MAIL_SERVER",
        "MAIL_PORT",
        "MAIL_USE_TLS",
        "MAIL_USE_SSL",
        "MAIL_USERNAME",
        "MAIL_PASSWORD",
        "MAIL_DEFAULT_SENDER",
    ]:
        monkeypatch.delenv(key, raising=False)

    monkeypatch.setattr(broker, "MAIL_SERVER", "smtp.config.local")
    monkeypatch.setattr(broker, "MAIL_PORT", 2526)
    monkeypatch.setattr(broker, "MAIL_USE_TLS", False)
    monkeypatch.setattr(broker, "MAIL_USE_SSL", True)
    monkeypatch.setattr(broker, "MAIL_USERNAME", "config-user@example.com")
    monkeypatch.setattr(broker, "MAIL_PASSWORD", "config-pass")
    monkeypatch.setattr(broker, "MAIL_DEFAULT_SENDER", "Config Sender <config@example.com>")

    settings = broker._resolve_mail_settings()

    assert settings.server == "smtp.config.local"
    assert settings.port == 2526
    assert settings.use_tls is False
    assert settings.use_ssl is True
    assert settings.username == "config-user@example.com"
    assert settings.password == "config-pass"
    assert settings.default_sender == "Config Sender <config@example.com>"


def test_disconnect_alert_mail_settings_env_username_sets_default_sender(monkeypatch):
    for key in [
        "MAIL_SERVER",
        "MAIL_PORT",
        "MAIL_USE_TLS",
        "MAIL_USE_SSL",
        "MAIL_USERNAME",
        "MAIL_PASSWORD",
        "MAIL_DEFAULT_SENDER",
    ]:
        monkeypatch.delenv(key, raising=False)

    monkeypatch.setattr(broker, "MAIL_SERVER", "smtp.config.local")
    monkeypatch.setattr(broker, "MAIL_PORT", 2526)
    monkeypatch.setattr(broker, "MAIL_USE_TLS", False)
    monkeypatch.setattr(broker, "MAIL_USE_SSL", True)
    monkeypatch.setattr(broker, "MAIL_USERNAME", "config-user@example.com")
    monkeypatch.setattr(broker, "MAIL_PASSWORD", "config-pass")
    monkeypatch.setattr(broker, "MAIL_DEFAULT_SENDER", "Config Sender <config@example.com>")

    monkeypatch.setenv("MAIL_USERNAME", "env-user@example.com")
    monkeypatch.setenv("MAIL_PASSWORD", "env-pass")

    settings = broker._resolve_mail_settings()

    assert settings.username == "env-user@example.com"
    assert settings.default_sender == "env-user@example.com"
