"""The AUTH_DEV_USER stub: a local-test convenience that hard-refuses
production-flagged environments (mirrors with's T-AZ-043), plus the
dev-only X-View-As perspective switch."""

import pytest
from fastapi.testclient import TestClient

from app.main import create_app
from tests.conftest import make_player


def test_stub_refuses_production(monkeypatch):
    monkeypatch.setenv("APP_ENV", "production")
    monkeypatch.setenv("AUTH_DEV_USER", "rian")
    with pytest.raises(RuntimeError, match="AUTH_DEV_USER"):
        create_app()


def test_production_without_stub_starts(monkeypatch):
    monkeypatch.setenv("APP_ENV", "production")
    monkeypatch.delenv("AUTH_DEV_USER", raising=False)
    assert create_app() is not None


def test_stub_resolves_identity_in_dev(monkeypatch):
    monkeypatch.setenv("APP_ENV", "dev")
    monkeypatch.setenv("AUTH_DEV_USER", "devuser")
    with TestClient(create_app(), base_url="https://testserver") as client:
        resp = client.get("/api/me")  # no session cookie at all
        assert resp.status_code == 200
        body = resp.json()
        assert body["username"] == "devuser"
        assert body["is_admin"] is False
        assert body["role"] == "player"


def test_no_stub_means_no_identity(client):
    # The suite's env (APP_ENV=test, no AUTH_DEV_USER) must not leak identity.
    assert client.get("/api/me").status_code == 401


def test_dev_stub_x_view_as_switches_perspective(monkeypatch, db_session):
    """The overnight perspective-check tool: under the stub as rian (app
    admin), an X-View-As header renders another player's perspective —
    still through the SAME policy verify (target must exist, no
    escalation)."""
    monkeypatch.setenv("APP_ENV", "dev")
    monkeypatch.setenv("AUTH_DEV_USER", "rian")
    make_player(db_session, "erin", display_name="Erin")
    with TestClient(create_app(), base_url="https://testserver") as client:
        body = client.get("/api/me", headers={"X-View-As": "erin"}).json()
        assert body["username"] == "rian"
        assert body["impersonating"] is True
        assert body["viewing_as"] == "erin"
        assert body["viewing_as_label"] == "Erin"
        assert body["real_user"] == "rian"
        assert body["can_write"] is False

        # A nonexistent target fail-closes to the real user.
        body = client.get("/api/me", headers={"X-View-As": "ghost"}).json()
        assert body["impersonating"] is False

        # No header -> plain rian.
        body = client.get("/api/me").json()
        assert body["impersonating"] is False
        assert body["username"] == "rian"
