"""Auth flow: register, login, refresh."""

from __future__ import annotations


def test_register_and_login(client, helpers):
    helpers.register(client, "alice@example.com")
    tokens = helpers.login(client, "alice@example.com")
    assert tokens["access_token"]
    assert tokens["refresh_token"]
    assert tokens["token_type"] == "bearer"
    # No workspace yet, so the access token has no active workspace.
    assert tokens["workspace_id"] is None


def test_duplicate_registration_conflicts(client, helpers):
    helpers.register(client, "bob@example.com")
    resp = client.post(
        "/auth/register",
        json={"email": "bob@example.com", "password": "password123", "name": "Bob"},
    )
    assert resp.status_code == 409


def test_login_with_wrong_password(client, helpers):
    helpers.register(client, "carol@example.com")
    resp = client.post("/auth/login", json={"email": "carol@example.com", "password": "nope"})
    assert resp.status_code == 401


def test_login_unknown_user(client):
    resp = client.post("/auth/login", json={"email": "ghost@example.com", "password": "whatever"})
    assert resp.status_code == 401


def test_short_password_rejected(client):
    resp = client.post(
        "/auth/register",
        json={"email": "shorty@example.com", "password": "123", "name": "S"},
    )
    assert resp.status_code == 422


def test_refresh_rotates_tokens(client, helpers):
    helpers.register(client, "dave@example.com")
    tokens = helpers.login(client, "dave@example.com")
    resp = client.post("/auth/refresh", json={"refresh_token": tokens["refresh_token"]})
    assert resp.status_code == 200
    refreshed = resp.json()
    assert refreshed["access_token"]
    assert refreshed["refresh_token"]


def test_access_token_cannot_be_used_as_refresh(client, helpers):
    helpers.register(client, "erin@example.com")
    tokens = helpers.login(client, "erin@example.com")
    resp = client.post("/auth/refresh", json={"refresh_token": tokens["access_token"]})
    assert resp.status_code == 401
