"""/api/view-as — enter/exit the app-layer impersonation (judgment #7).
Enter is super-admin only and strict (bogus targets 404 — T-VAS-12
rebuild inversion); both directions write audit rows recording both
identities (T-AZ-031)."""

from __future__ import annotations

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

from app.routers.deps import ActorDep, SessionDep
from app.services.authz.view_as import (
    VIEW_AS_COOKIE,
    VIEW_AS_TTL,
    ViewAsError,
    enter_view_as,
    exit_view_as,
)

router = APIRouter()


class EnterViewAs(BaseModel):
    username: str


@router.post("/api/view-as")
def enter(body: EnterViewAs, session: SessionDep, actor: ActorDep) -> JSONResponse:
    try:
        target = enter_view_as(session, actor, body.username)
    except ViewAsError as e:
        return JSONResponse(
            status_code=e.status,
            content={"error_code": e.code, "summary": e.summary, "detail": e.detail},
        )
    resp = JSONResponse({"ok": True, "viewing_as": target.idauth_username})
    resp.set_cookie(
        VIEW_AS_COOKIE,
        target.idauth_username,
        max_age=VIEW_AS_TTL,
        httponly=True,
        secure=True,
        samesite="lax",
        path="/",
    )
    return resp


@router.delete("/api/view-as")
def leave(session: SessionDep, actor: ActorDep) -> JSONResponse:
    """Exit is never blockable — clearing the cookie must always work,
    whatever state the impersonation is in."""
    exit_view_as(session, actor)
    resp = JSONResponse({"ok": True})
    resp.delete_cookie(VIEW_AS_COOKIE, path="/")
    return resp
