"""/api/tenant — switch the request-scoped current tenant (ADR #015).

Switching the current tenant is a NAVIGATION PREFERENCE (like picking a
saved view), so it is deliberately NOT audited. POST validates the slug
against the actor's allowed set (membership is server truth), sets the
HttpOnly ``with_tenant`` cookie, and echoes the new current tenant.

Because switching only changes which tenant the cookie points at — and
every query already flows through ``scope(actor)`` with the actor's
``tenant_id`` — there is nothing to invalidate server-side.

  POST /api/tenant {slug}  -> 200 {tenant:{slug,name}}     valid switch
                           -> 403 TENANT_FORBIDDEN          unknown/forbidden slug
"""

from __future__ import annotations

from fastapi import APIRouter
from pydantic import BaseModel
from starlette.responses import JSONResponse

from app.routers.deps import ActorDep
from app.services.authz.context import TENANT_COOKIE

router = APIRouter()

# A persistent nav preference — outlives the app session (which re-mints
# every 12h). The server is the only reader (HttpOnly), so a value that
# points at a since-revoked tenant simply falls back at resolve time.
TENANT_COOKIE_MAX_AGE = 365 * 24 * 60 * 60


class SwitchTenant(BaseModel):
    slug: str


@router.post("/api/tenant")
def switch_tenant(body: SwitchTenant, actor: ActorDep) -> JSONResponse:
    slug = (body.slug or "").strip()
    match = next((t for t in actor.allowed_tenants if t.slug == slug), None)
    if match is None:
        return JSONResponse(
            status_code=403,
            content={
                "error_code": "TENANT_FORBIDDEN",
                "summary": "You don't have access to that tenant",
                "detail": "Pick a tenant from your own list. If you think you "
                "should have access, ask an owner to add you to those books.",
            },
        )
    resp = JSONResponse({"tenant": {"slug": match.slug, "name": match.name}})
    resp.set_cookie(
        TENANT_COOKIE,
        match.slug,
        max_age=TENANT_COOKIE_MAX_AGE,
        httponly=True,
        secure=True,
        samesite="lax",
        path="/",
    )
    return resp
