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_role::RoleTree};
use phono_models::{
    accessors::{Accessor as _, Actor, workspace::WorkspaceAccessor},
    service_cred::ServiceCred,
};
use redact::Secret;
use serde::Deserialize;
use url::Url;
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 the page at which a user manages their service
/// credentials for a workspace.
#[debug_handler(state = crate::app::App)]
pub(super) async fn get(
    State(settings): State<Settings>,
    State(mut pooler): State<WorkspacePooler>,
    CurrentUser(user): CurrentUser,
    AppDbConn(mut app_db): AppDbConn,
    Path(PathParams { workspace_id }): Path<PathParams>,
    navigator: Navigator,
) -> Result<impl IntoResponse, AppError> {
    // Mutex is required to use client in async closures.
    let workspace_client = Mutex::new(
        pooler
            .acquire_for(workspace_id, RoleAssignment::User(user.id))
            .await?,
    );

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

    let cluster = workspace.fetch_cluster(&mut app_db).await?;

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

    struct ServiceCredInfo {
        conn_string: Secret<Url>,
        conn_string_redacted: String,
        permissions_editor: PermissionsEditor,
    }

    let service_cred_info = stream::iter(
        ServiceCred::belonging_to_user(user.id)
            .fetch_all(&mut app_db)
            .await?,
    )
    .then(async |cred| {
        let current_perms: HashSet<RelPermission> = stream::iter({
            // Guard must be assigned to a local variable,
            // lest the mutex become deadlocked.
            let mut locked_client = workspace_client.lock().await;
            RoleTree::granted_to_rolname(&cred.rolname)
                .fetch_tree(&mut locked_client)
                .await?
                .ok_or(anyhow!("listing roles for service cred: role tree is None"))?
                .flatten_inherited()
                .into_iter()
                .filter(|role| role.role.rolname != cred.rolname)
        })
        .then(async |role| {
            let mut locked_client = workspace_client.lock().await;
            RelPermission::from_rolname(&role.role.rolname, &mut locked_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();
        let conn_string = cluster.conn_str_for_db(
            &workspace.db_name,
            Some((
                cred.rolname.as_str(),
                Secret::new(cred.password.expose_secret().as_str()),
            )),
        )?;
        Ok(ServiceCredInfo {
            conn_string,
            conn_string_redacted: "postgresql://********".to_owned(),
            permissions_editor: PermissionsEditor {
                update_endpoint: format!(
                    "{cred_id}/update-permissions",
                    cred_id = cred.id.simple()
                ),
                current_perms,
                target: Grantee::ServiceCred(cred),
                include_owner: false,
                all_rels: all_rels.clone(),
                hidden_inputs: [].into(),
            },
        })
    })
    .collect::<Vec<Result<ServiceCredInfo, AppError>>>()
    .await
    .into_iter()
    .collect::<Result<Vec<ServiceCredInfo>, AppError>>()?;

    #[derive(Template)]
    #[template(path = "workspaces_single/service_credentials.html")]
    struct ResponseTemplate {
        service_cred_info: Vec<ServiceCredInfo>,
        settings: Settings,
        workspace_nav: WorkspaceNav,
    }

    let mut locked_client = workspace_client
        .try_lock()
        .ok_or(anyhow!("mutex should be unlocked"))?;
    Ok(Html(
        ResponseTemplate {
            workspace_nav: WorkspaceNav::builder()
                .navigator(navigator)
                .workspace(workspace.clone())
                .populate_rels(&mut app_db, &mut locked_client)
                .await?
                .build()?,
            service_cred_info,
            settings,
        }
        .render()?,
    ))
}
