"""Schritt 1: additiver Ein-Klick-Login per Capability-Token (Cookie / ?k=)."""

from fastapi.testclient import TestClient

import app.dependencies as deps
from app.main import app
from app.config import settings

client = TestClient(app)


def test_capability_link_sets_cookie_and_strips_url(monkeypatch):
    monkeypatch.setattr(settings, "auth_enabled", True)
    user, token = deps.get_store().create_user("Senior")
    r = client.get(f"/?k={token}", follow_redirects=False)
    assert r.status_code == 303
    # Cookie wird gesetzt
    sc = r.headers.get("set-cookie", "")
    assert "va_token=" in sc and "HttpOnly" in sc
    # URL ist um ?k= bereinigt (Redirect-Ziel ohne k)
    assert "k=" not in r.headers.get("location", "")
    client.cookies.clear()


def test_cookie_authenticates_api(monkeypatch):
    monkeypatch.setattr(settings, "auth_enabled", True)
    user, token = deps.get_store().create_user("Senior")
    client.cookies.set("va_token", token)
    me = client.get("/api/me")
    assert me.status_code == 200
    assert me.json()["user_id"] == user.id
    client.cookies.clear()


def test_query_token_authenticates_api(monkeypatch):
    monkeypatch.setattr(settings, "auth_enabled", True)
    user, token = deps.get_store().create_user("Senior")
    me = client.get(f"/api/me?k={token}")
    assert me.status_code == 200
    assert me.json()["user_id"] == user.id


def test_invalid_capability_link_does_not_set_cookie(monkeypatch):
    monkeypatch.setattr(settings, "auth_enabled", True)
    r = client.get("/?k=not-a-real-token", follow_redirects=False)
    # ungültiges Token -> kein Cookie, kein 303-Redirect auf bereinigte URL
    assert "va_token=" not in r.headers.get("set-cookie", "")
    client.cookies.clear()


def test_db_admin_flag_grants_admin_via_me(monkeypatch):
    monkeypatch.setattr(settings, "auth_enabled", True)
    store = deps.get_store()
    user, token = store.create_user("Caregiver")
    store.set_user_admin(user.id, True)
    client.cookies.set("va_token", token)
    me = client.get("/api/me").json()
    assert me["is_admin"] is True
    client.cookies.clear()
