use askama::Template;
use axum::{
    debug_handler,
    extract::{Path, State},
    response::{Html, IntoResponse},
};
use phono_models::{
    accessors::{Accessor as _, Actor, workspace::WorkspaceAccessor},
    workspace::Workspace,
};
use serde::Deserialize;
use uuid::Uuid;

use crate::{
    app::AppDbConn,
    errors::AppError,
    navigator::Navigator,
    settings::Settings,
    user::CurrentUser,
    workspace_nav::WorkspaceNav,
    workspace_pooler::{RoleAssignment, WorkspacePooler},
};

#[derive(Debug, Deserialize)]
pub(super) struct PathParams {
    workspace_id: Uuid,
}

/// HTTP GET handler for a top-level workspace navigation page. At the moment,
/// this is pretty spare---essentially the workspace navigation sidebar blown
/// up to the size of a full page.
#[debug_handler(state = crate::app::App)]
pub(super) async fn get(
    State(settings): State<Settings>,
    CurrentUser(user): CurrentUser,
    AppDbConn(mut app_db): AppDbConn,
    Path(PathParams { workspace_id }): Path<PathParams>,
    navigator: Navigator,
    State(mut pooler): State<WorkspacePooler>,
) -> Result<impl IntoResponse, AppError> {
    let mut workspace_client = pooler
        .acquire_for(workspace_id, RoleAssignment::User(user.id))
        .await?;

    let workspace = WorkspaceAccessor::new()
        .id(workspace_id)
        .as_actor(Actor::User(user.id))
        .using_app_db(&mut app_db)
        .using_workspace_client(&mut workspace_client)
        .fetch_one()
        .await?;

    #[derive(Template)]
    #[template(path = "workspaces_single/nav.html")]
    struct ResponseTemplate {
        settings: Settings,
        workspace: Workspace,
        workspace_nav: WorkspaceNav,
    }

    Ok(Html(
        ResponseTemplate {
            workspace_nav: WorkspaceNav::builder()
                .navigator(navigator)
                .workspace(workspace.clone())
                .populate_rels(&mut app_db, &mut workspace_client)
                .await?
                .build()?,
            settings,
            workspace,
        }
        .render()?,
    ))
}
