from __future__ import annotations

from fastapi import APIRouter, Request
from fastapi.responses import RedirectResponse

from app.core.db.common import CommonSessionLocal
from app.core.security.csrf import get_or_create_csrf_token
from app.core.security.session_auth import get_current_user
from app.core.templating import templates
from app.modules.core.rbac.deps import get_user_permissions, get_user_roles
from app.modules.workspace_navigation.service import build_workspace_cards, current_workspace_code

router = APIRouter(tags=["workspace-navigation-ui"])


@router.get("/workspaces")
def workspaces(request: Request):
    db = CommonSessionLocal()
    try:
        current_user = get_current_user(request, db=db)
        if not current_user:
            return RedirectResponse(url="/login", status_code=303)

        roles = get_user_roles(db, current_user.id)
        permissions = get_user_permissions(db, current_user.id)
        cards = build_workspace_cards(roles, permissions)
        current_path = request.url.path

        return templates.TemplateResponse(
            "modules/workspace_navigation/templates/workspace_navigation/index.html",
            {
                "request": request,
                "current_user": current_user,
                "current_user_roles": roles,
                "current_user_permissions": permissions,
                "csrf_token": get_or_create_csrf_token(request),
                "title": "My Workspaces",
                "workspace_cards": cards,
                "current_workspace_code": current_workspace_code(current_path),
            },
        )
    finally:
        db.close()
