use askama::Template;
use axum::{
    extract::State,
    response::{Html, IntoResponse},
};
use phono_models::workspace_user_perm::WorkspaceMembership;

use crate::{
    app::AppDbConn,
    errors::AppError,
    navigator::{Navigator, NavigatorPage as _},
    settings::Settings,
    user::CurrentUser,
};

pub(super) async fn get(
    State(settings): State<Settings>,
    CurrentUser(user): CurrentUser,
    navigator: Navigator,
    AppDbConn(mut app_db): AppDbConn,
) -> Result<impl IntoResponse, AppError> {
    // Workspace memberships may be pulled directly from the cache table without
    // additional auth checks in this case, because at worst it should only
    // inaccurately give the user the impression that they still have access to
    // a previously visible workspace. In a specific failure mode, this may
    // allow the user to continue seeing updates to the workspace name after
    // access has been revoked, until the cache record is cleared, e.g. by the
    // user attempting to actually access the data of the workspace. This isn't
    // ideal, but it should only happen under exceedingly rare circumstances and
    // in those cases is not expected to be catastrophic.
    let workspace_perms = WorkspaceMembership::belonging_to_user(user.id)
        .fetch_all(&mut app_db)
        .await?;

    #[derive(Template)]
    #[template(path = "workspaces_multi/list.html")]
    struct ResponseTemplate {
        navigator: Navigator,
        settings: Settings,
        workspace_perms: Vec<WorkspaceMembership>,
    }

    Ok(Html(
        ResponseTemplate {
            navigator,
            settings,
            workspace_perms,
        }
        .render()?,
    ))
}
