"""
app/api/v1/workspaces.py — workspace 切换路由
POST /workspaces/switch → /api/v1/workspaces/switch（契约路径）
从 auth.py 独立出来，避免 /auth 前缀错误。
"""

from typing import Annotated

from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy.orm import Session

from app.core.security import create_access_token
from app.core.database import get_db
from app.core.response import ok, raise_forbidden
from app.middleware.workspace_guard import CurrentUser, get_current_user
from app.models.workspace import WorkspaceMember

router = APIRouter(tags=["workspaces"])


class SwitchWorkspaceRequest(BaseModel):
    workspace_id: int


@router.post("/workspaces/switch")
def switch_workspace(
    body: SwitchWorkspaceRequest,
    current_user: Annotated[CurrentUser, Depends(get_current_user)],
    db: Session = Depends(get_db),
):
    """切换当前 workspace（必须查 membership 校验）。"""
    member = db.query(WorkspaceMember).filter(
        WorkspaceMember.user_id == current_user.user_id,
        WorkspaceMember.workspace_id == body.workspace_id,
    ).first()
    if not member:
        raise_forbidden("无权访问目标 workspace")
    token = create_access_token(current_user.user_id, body.workspace_id, member.role)
    return ok({
        "current_workspace_id": body.workspace_id,
        "token": token,
    })
