

# ---------------------------------------------------------------------------
# Auth
# ---------------------------------------------------------------------------
class TestAuth:
    def test_me_shape(self, api):
        r = api.get("/auth/me")
        assert r.status_code == 200
        u = r.json()
        assert u["email"] == api.email
        assert "password" not in u and "password_hash" not in u

    def test_me_requires_auth(self, api):
        r = api.get("/auth/me", cookies={})
        assert r.status_code == 401

    def test_login_wrong_password(self, api):
        r = api.post("/auth/login", json={"email": api.email, "password": "Wrong#Pass123"},
                     headers=H(api))
        assert r.status_code == 401

    def test_login_unknown_user(self, api):
        r = api.post("/auth/login", json={"email": "nobody@x.com", "password": "Whatever#123"},
                     headers=H(api))
        assert r.status_code == 401

    def test_short_password_rejected(self, api):
        r = api.post("/auth/register",
                     json={"email": f"s{uuid.uuid4().hex[:8]}@x.com", "password": "short"},
                     headers=H(api))
        assert r.status_code in (400, 422)

    def test_duplicate_email_rejected(self, api):
        r = api.post("/auth/register", json={"email": api.email, "password": "Another#12345"},
                     headers=H(api))
        assert r.status_code in (400, 409, 422)

    def test_csrf_required_on_post(self, api):
        r = api.post("/auth/logout", headers={"X-CSRF-Token": ""})
        assert r.status_code in (401, 403)

    def test_csrf_wrong_token_rejected(self, api):
        r = api.post("/auth/logout", headers={"X-CSRF-Token": "forged-token"})
        assert r.status_code in (401, 403)

    def test_session_cookie_present_and_httponly(self, api):
        names = [c.name for c in api.cookies.jar]
        assert "mailer_session" in names
        r = api.post("/auth/login", json={"email": api.email, "password": api.password},
                     headers=H(api))
