use std::collections::HashSet;

use anyhow::anyhow;
use askama::Template;
use axum::{
    debug_handler,
    extract::{Path, State},
    response::{Html, IntoResponse},
};
use futures::{lock::Mutex, prelude::*, stream};
use phono_backends::{
    pg_class::PgClass,
    pg_database::PgDatabase,
    pg_role::{RoleTree, user_id_from_rolname},
    rolnames::ROLE_PREFIX_USER,
};
use phono_models::{
    accessors::{Accessor as _, Actor, workspace::WorkspaceAccessor},
    user::User,
    workspace::Workspace,
};
use serde::Deserialize;
use uuid::Uuid;

use crate::{
    app::AppDbConn,
    errors::AppError,
    navigator::Navigator,
    permissions::{Grantee, PermissionsEditor, RelPermission},
    settings::Settings,
    user::CurrentUser,
    workspace_nav::WorkspaceNav,
    workspace_pooler::{RoleAssignment, WorkspacePooler},
    workspaces::PHONO_TABLE_NAMESPACE,
};

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

/// HTTP GET handler for workspace settings, including renaming, access control,
/// and deletion.
#[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?;

    // TODO: Limit access to workspace "owners" or equivalent.
    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?;

    let database = PgDatabase::current()
        .fetch_one(&mut workspace_client)
        .await?;

    // WARNING: For performance and simplicity, this does not resolve inherited
    // `CONNECT` permissions. This is acceptable so long as Phonograph does not
    // begin granting `CONNECT` permissions to roles which are inherited from.
    // TODO: Resolve inherited permissions anyways, for the sake of defensive
    // programming.
    let collaborator_users = User::with_id_in(
        database
            .datacl
            .unwrap_or(vec![])
            .iter()
            .flat_map(|acl_item| user_id_from_rolname(&acl_item.grantee).ok()),
    )
    .fetch_all(&mut app_db)
    .await?;

    let all_rels: Vec<_> = PgClass::belonging_to_namespace(PHONO_TABLE_NAMESPACE)
        .fetch_all(&mut workspace_client)
        .await?
        .into_iter()
        .filter(|rel| rel.relkind == 'r' as i8)
        .collect();

    let app_db_mutex = Mutex::new(app_db);
    let workspace_client_mutex = Mutex::new(workspace_client);
    let collaborators: Vec<PermissionsEditor> = stream::iter(collaborator_users)
        .then(async |target_user| -> Result<PermissionsEditor, AppError> {
            let target_rolname = format!("{ROLE_PREFIX_USER}{id}", id = target_user.id.simple());
            let current_perms: HashSet<RelPermission> = stream::iter({
                // Guard must be assigned to a local variable,
                // lest the mutex become deadlocked.
                let mut workspace_client = workspace_client_mutex.lock().await;
                RoleTree::granted_to_rolname(&target_rolname)
                    .fetch_tree(&mut workspace_client)
                    .await?
                    .ok_or(anyhow!("listing roles for user: role tree is None"))?
                    .flatten_inherited()
                    .into_iter()
                    .filter(|role| role.role.rolname != target_rolname)
            })
            .then(async |role| {
                let mut workspace_client = workspace_client_mutex.lock().await;
                RelPermission::from_rolname(&role.role.rolname, &mut workspace_client).await
            })
            .collect::<Vec<Result<_, _>>>()
            .await
            .into_iter()
            // [`futures::stream::StreamExt::collect`]
            // can only collect to types that implement [`Default`],
            // so we must do result handling with the sync version of `collect()`.
            .collect::<Result<Vec<_>, _>>()?
            .into_iter()
            .flatten()
            .collect();
            Ok(PermissionsEditor {
                current_perms,
                update_endpoint: "update-rel-privileges".to_owned(),
                include_owner: true,
                all_rels: all_rels.clone(),
                hidden_inputs: [("user_id".to_owned(), target_user.id.simple().to_string())].into(),
                target: Grantee::User(target_user),
            })
        })
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .collect::<Result<Vec<_>, AppError>>()?;

    let mut app_db = app_db_mutex.into_inner();
    let mut workspace_client = workspace_client_mutex.into_inner();

    let workspace_nav = WorkspaceNav::builder()
        .navigator(navigator)
        .workspace(workspace.clone())
        .populate_rels(&mut app_db, &mut workspace_client)
        .await?
        .build()?;

    #[derive(Debug, Template)]
    #[template(path = "workspaces_single/settings.html")]
    struct ResponseTemplate {
        collaborators: Vec<PermissionsEditor>,
        settings: Settings,
        workspace: Workspace,
        workspace_nav: WorkspaceNav,
    }
    Ok(Html(
        ResponseTemplate {
            collaborators,
            workspace_nav,
            workspace,
            settings,
        }
        .render()?,
    ))
}
