"""Workspace-profile selection on /api/me (ADR #020, tenant modes phase 1).

The name defaults BY SLUG (plusroi -> "plusroi", else "bowden-works"), can be
overridden per tenant via ``settings.workspace_profile``, follows a tenant
switch, and safely defaults for a NO_TENANT user. The SPA turns this name into
the actual profile object — so this backend surface is just the selector."""

from __future__ import annotations

import pytest
from sqlalchemy import select

from app.models import Party, Tenant


@pytest.fixture()
def rian(client_factory):
    return client_factory("rian", is_super_admin=True)


@pytest.fixture()
def bob(client_factory):
    return client_factory("bob")


def test_defaults_by_slug(rian, bob):
    # rian's current tenant is bowden-works; bob is a PlusROI-only owner.
    assert rian.get("/api/me").json()["workspace_profile"] == "bowden-works"
    assert bob.get("/api/me").json()["workspace_profile"] == "plusroi"


def test_follows_tenant_switch(rian):
    rian.post("/api/tenant", json={"slug": "plusroi"})
    assert rian.get("/api/me").json()["workspace_profile"] == "plusroi"


def test_setting_overrides_slug_default(rian, session):
    # rian's current tenant is bowden-works; a stored setting overrides the
    # slug default. Fetch the row fresh (the graph fixture's ORM objects are
    # detached from their session-scoped Session).
    tenant = session.scalar(
        select(Tenant)
        .join(Party, Party.id == Tenant.party_id)
        .where(Party.slug == "bowden-works")
    )
    tenant.settings = {"workspace_profile": "custom-mode"}
    session.commit()
    try:
        assert rian.get("/api/me").json()["workspace_profile"] == "custom-mode"
    finally:
        tenant.settings = {}
        session.commit()


def test_no_tenant_user_gets_default(client_factory):
    nobody = client_factory("nobody")
    assert nobody.get("/api/me").json()["workspace_profile"] == "bowden-works"
