"""Tests for login IP allowlist precheck and shared helpers."""
from unittest.mock import patch

import pytest

from server.utils import login_allowlist as la


def test_allowlist_disabled_always_allowed():
    with patch.object(la.settings, "LOGIN_ALLOWLIST_ENABLED", "false"):
        enabled, allowed, msg = la.check_login_ip("1.2.3.4")
    assert enabled is False
    assert allowed is True
    assert msg is None


def test_allowlist_enabled_ip_allowed():
    with patch.object(la.settings, "LOGIN_ALLOWLIST_ENABLED", "true"), patch.object(
        la.settings, "LOGIN_SUBSCRIPTION_IPS", ""
    ), patch.object(la.settings, "LOGIN_MANUAL_IPS", "1.2.3.4,10.0.0.0/8"):
        enabled, allowed, msg = la.check_login_ip("1.2.3.4")
    assert enabled is True
    assert allowed is True
    assert msg is None


def test_allowlist_enabled_ip_blocked():
    with patch.object(la.settings, "LOGIN_ALLOWLIST_ENABLED", "true"), patch.object(
        la.settings, "LOGIN_SUBSCRIPTION_IPS", ""
    ), patch.object(la.settings, "LOGIN_MANUAL_IPS", "203.0.113.1"):
        enabled, allowed, msg = la.check_login_ip("198.51.100.9")
    assert enabled is True
    assert allowed is False
    assert msg and "198.51.100.9" in msg


def test_allowlist_cidr_match():
    with patch.object(la.settings, "LOGIN_ALLOWLIST_ENABLED", "true"), patch.object(
        la.settings, "LOGIN_SUBSCRIPTION_IPS", ""
    ), patch.object(la.settings, "LOGIN_MANUAL_IPS", "10.0.0.0/8"):
        assert la.ip_in_allowlist("10.1.2.3", la.get_allowed_login_ips()) is True


def test_allowlist_empty_list_not_enforced():
    with patch.object(la.settings, "LOGIN_ALLOWLIST_ENABLED", "true"), patch.object(
        la.settings, "LOGIN_SUBSCRIPTION_IPS", ""
    ), patch.object(la.settings, "LOGIN_MANUAL_IPS", ""):
        enabled, allowed, msg = la.check_login_ip("1.2.3.4")
    assert enabled is True
    assert allowed is True


def test_login_access_endpoint_allowed_sync():
    from fastapi.testclient import TestClient
    from server.main import app

    client = TestClient(app)
    res = client.get("/api/auth/login-access")
    assert res.status_code == 200
    data = res.json()
    assert data == {"allowed": True}
    assert "client_ip" not in data
    assert "allowlist_enabled" not in data


def test_login_access_blocked_when_not_whitelisted_sync():
    from fastapi.testclient import TestClient
    from server.main import app

    with patch.object(la.settings, "LOGIN_ALLOWLIST_ENABLED", "true"), patch.object(
        la.settings, "LOGIN_SUBSCRIPTION_IPS", ""
    ), patch.object(la.settings, "LOGIN_MANUAL_IPS", "203.0.113.1"), patch(
        "server.api.auth.get_client_ip", return_value="198.51.100.9"
    ):
        client = TestClient(app)
        res = client.get("/api/auth/login-access")
    assert res.status_code == 403
    assert res.content == b""
