use axum::{
    debug_handler,
    extract::{Path, State},
    response::IntoResponse,
};
use phono_backends::rolnames::{
    ROLE_PREFIX_SERVICE_CRED, SERVICE_CRED_CONN_LIMIT, SERVICE_CRED_SUFFIX_LEN,
};
use phono_models::{
    accessors::{Accessor as _, Actor, workspace::WorkspaceAccessor},
    service_cred::ServiceCred,
};
use phono_pestgros::escape_identifier;
use rand::distributions::{Alphanumeric, DistString};
use redact::Secret;
use serde::Deserialize;
use sqlx::query;
use uuid::Uuid;

use crate::{
    app::AppDbConn,
    errors::AppError,
    navigator::{Navigator, NavigatorPage},
    user::CurrentUser,
    workspace_pooler::{RoleAssignment, WorkspacePooler},
    workspaces::PHONO_TABLE_NAMESPACE,
};

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

/// HTTP POST handler for generating a new "service credential" role for a user
/// and workspace.
#[debug_handler(state = crate::app::App)]
pub(super) async fn post(
    State(mut pooler): State<WorkspacePooler>,
    AppDbConn(mut app_db): AppDbConn,
    CurrentUser(user): CurrentUser,
    navigator: Navigator,
    Path(PathParams { workspace_id }): Path<PathParams>,
) -> Result<impl IntoResponse, AppError> {
    // FIXME: CSRF

    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?;

    let rolname = format!(
        "{ROLE_PREFIX_SERVICE_CRED}{uid}_{suffix}",
        uid = user.id.simple(),
        suffix = Alphanumeric
            .sample_string(&mut rand::thread_rng(), SERVICE_CRED_SUFFIX_LEN)
            // FIXME: exclude uppercase letters from the original distribution.
            // This is a quick, dirty, and arguably incorrect hack for expediency.
            .to_lowercase(),
    );

    let password = Secret::new(format!("phpwd{0}", Uuid::new_v4().simple()));

    assert!(!password.expose_secret().contains('\'') && !password.expose_secret().contains('\\'));
    query(&format!(
        "create user {rolname_esc} password '{password_dangerous}' connection limit {SERVICE_CRED_CONN_LIMIT}",
        password_dangerous = password.expose_secret(),
        rolname_esc = escape_identifier(&rolname)
    ))
    .execute(workspace_client.get_conn())
    .await?;

    query(&format!(
        "grant connect on database {db_name} to {rolname_esc}",
        db_name = workspace.db_name,
        rolname_esc = escape_identifier(&rolname)
    ))
    .execute(workspace_client.get_conn())
    .await?;
    query(&format!(
        "grant usage on schema {nsp} to {rolname_esc}",
        nsp = PHONO_TABLE_NAMESPACE,
        rolname_esc = escape_identifier(&rolname)
    ))
    .execute(workspace_client.get_conn())
    .await?;

    ServiceCred::insert()
        .cluster_id(workspace.cluster_id)
        .owner_id(user.id)
        .rolname(rolname)
        .password(password)
        .build()?
        .execute(&mut app_db)
        .await?;

    Ok(navigator
        .workspace_page()
        .workspace_id(workspace_id)
        .suffix("service-credentials/")
        .build()?
        .redirect_to())
}
