"""Workspace create / list / switch."""

from __future__ import annotations

import uuid


def test_create_workspace_makes_creator_owner(client, helpers):
    ctx = helpers.bootstrap_owner(client)
    assert ctx["workspace"]["role"] == "owner"
    assert ctx["workspace"]["slug"] == "acme"


def test_list_workspaces_only_shows_own(client, helpers):
    ctx = helpers.bootstrap_owner(client, email="owner@example.com")
    resp = client.get("/workspaces", headers=helpers.headers(ctx["access_token"]))
    assert resp.status_code == 200
    workspaces = resp.json()
    assert len(workspaces) == 1
    assert workspaces[0]["role"] == "owner"


def test_slug_is_unique(client, helpers):
    ctx = helpers.bootstrap_owner(client)
    second = helpers.create_workspace(client, ctx["access_token"], name="Acme")
    assert second["workspace"]["slug"] != "acme"
    assert second["workspace"]["slug"].startswith("acme")


def test_switch_to_member_workspace(client, helpers):
    ctx = helpers.bootstrap_owner(client)
    ws_id = ctx["workspace"]["id"]
    # Token from plain login has no workspace; switching grants a scoped token.
    tokens = helpers.login(client, ctx["user_email"])
    resp = client.post(
        f"/workspaces/{ws_id}/switch", headers=helpers.headers(tokens["access_token"])
    )
    assert resp.status_code == 200
    assert resp.json()["workspace_id"] == ws_id


def test_switch_to_non_member_workspace_forbidden(client, helpers):
    ctx = helpers.bootstrap_owner(client)
    stranger_ws = uuid.uuid4()
    resp = client.post(
        f"/workspaces/{stranger_ws}/switch",
        headers=helpers.headers(ctx["access_token"]),
    )
    assert resp.status_code == 403


def test_workspace_endpoints_require_auth(client):
    assert client.get("/workspaces").status_code in (401, 403)
