"""
Integration tests for Auth Core module
Validates hashing, token issuance, FastAPI health wiring, and pepper guidance

Auto-generated by RapidKit - Auth Core Module
"""

from __future__ import annotations

import importlib
import importlib.util

import pytest


pytestmark = [pytest.mark.integration, pytest.mark.template_integration]

from src.modules.free.auth.core.auth.core import AuthCoreRuntime, load_settings  # type: ignore[import]
from src.health.auth_core import register_auth_core_health  # type: ignore[import]


PEPPER_VALUE = "integration-test-static-pepper"


def _prepare_runtime(monkeypatch: pytest.MonkeyPatch) -> AuthCoreRuntime:
    monkeypatch.setenv("RAPIDKIT_AUTH_CORE_PEPPER", PEPPER_VALUE)
    settings = load_settings()
    return AuthCoreRuntime(settings)


def test_password_hash_and_verify(monkeypatch: pytest.MonkeyPatch) -> None:
    """Hash a valid password and ensure verification succeeds."""

    runtime = _prepare_runtime(monkeypatch)
    password = "ValidPassword123"

    encoded = runtime.hash_password(password)

    assert isinstance(encoded, str)
    assert encoded.count("$") == 4
    assert runtime.verify_password(password, encoded) is True
    assert runtime.verify_password("WrongPassword", encoded) is False


@pytest.mark.parametrize(
    "candidate",
    [
        "short",
        "alllowercasepassword",
        "ALLUPPERCASE123",
        "NoDigitsHere",
    ],
)
def test_password_policy_enforced(candidate: str, monkeypatch: pytest.MonkeyPatch) -> None:
    """Ensure weak passwords raise a ValueError before hashing."""

    runtime = _prepare_runtime(monkeypatch)

    with pytest.raises(ValueError):
        runtime.hash_password(candidate)


def test_issue_and_verify_token(monkeypatch: pytest.MonkeyPatch) -> None:
    """Issue a token and verify signature & payload integrity."""

    runtime = _prepare_runtime(monkeypatch)

    token = runtime.issue_token(
        "user-123",
        audience="api",
        scopes=("read", "write"),
        ttl_seconds=60,
        custom_claims={"role": "admin"},
    )

    payload = runtime.verify_token(token)

    assert payload["sub"] == "user-123"
    assert payload["aud"] == "api"
    assert payload["scopes"] == ["read", "write"]
    assert payload["role"] == "admin"


def test_token_expiration(monkeypatch: pytest.MonkeyPatch) -> None:
    """Expired tokens should raise ValueError during verification."""

    runtime = _prepare_runtime(monkeypatch)
    token = runtime.issue_token("user-123", ttl_seconds=1)

    auth_core_module = importlib.import_module("src.modules.free.auth.core.auth.core")
    original_time = auth_core_module.time.time

    def fake_time() -> float:
        return original_time() + 10

    monkeypatch.setattr(auth_core_module.time, "time", fake_time)

    with pytest.raises(ValueError):
        runtime.verify_token(token)


def test_metadata_reflects_pepper(monkeypatch: pytest.MonkeyPatch) -> None:
    """Metadata should expose pepper configuration details."""

    runtime = _prepare_runtime(monkeypatch)
    metadata = runtime.metadata()

    assert metadata["pepper_env"] == "RAPIDKIT_AUTH_CORE_PEPPER"
    assert metadata["pepper_configured"] is True
    assert metadata["token_ttl_seconds"] > 0


@pytest.mark.skipif(
    importlib.util.find_spec("fastapi") is None,
    reason="FastAPI not installed",
)
def test_auth_core_health_router_registration(monkeypatch: pytest.MonkeyPatch) -> None:
    """Register the Auth Core health router and ensure the route is exposed."""

    from fastapi import FastAPI

    monkeypatch.setenv("RAPIDKIT_AUTH_CORE_PEPPER", PEPPER_VALUE)

    app = FastAPI()
    register_auth_core_health(app)

    paths = {route.path for route in app.routes}
    assert "/api/health/module/auth-core" in paths


@pytest.mark.skipif(
    importlib.util.find_spec("fastapi") is None,
    reason="FastAPI not installed",
)
def test_auth_core_health_endpoint_payload(monkeypatch: pytest.MonkeyPatch) -> None:
    """Invoke the Auth Core health endpoint and validate payload fields."""

    from fastapi import FastAPI, status
    from fastapi.testclient import TestClient

    monkeypatch.setenv("RAPIDKIT_AUTH_CORE_PEPPER", PEPPER_VALUE)

    app = FastAPI()
    register_auth_core_health(app)

    client = TestClient(app)
    response = client.get("/api/health/module/auth-core")

    assert response.status_code == status.HTTP_200_OK
    payload = response.json()
    assert payload["status"] == "ok"
    assert payload["module"] == "auth_core"
    assert payload["pepper_configured"] is True
