use axum::{
    debug_handler,
    extract::{Path, State},
    response::IntoResponse,
};
use phono_backends::{pg_database::PgDatabase, rolnames::ROLE_PREFIX_USER};
use phono_models::{
    accessors::{Accessor as _, Actor, workspace::WorkspaceAccessor},
    user::User,
    workspace_user_perm::WorkspaceMembership,
};
use phono_pestgros::escape_identifier;
use serde::Deserialize;
use sqlx::query;
use uuid::Uuid;
use validator::Validate;

use crate::{
    app::AppDbConn,
    errors::AppError,
    extractors::ValidatedForm,
    navigator::{Navigator, NavigatorPage as _},
    user::CurrentUser,
    workspace_pooler::{RoleAssignment, WorkspacePooler},
};

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

#[derive(Debug, Deserialize, Validate)]
pub(super) struct FormBody {
    email: String,
}

/// HTTP POST handler for granting another user (or future user with matching
/// email) access to a 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>,
    ValidatedForm(form): ValidatedForm<FormBody>,
) -> Result<impl IntoResponse, AppError> {
    // FIXME: CSRF

    let mut workspace_client = pooler
        .acquire_for(workspace_id, RoleAssignment::User(user.id))
        .await?;

    WorkspaceAccessor::new()
        .id(workspace_id)
        .as_actor(Actor::User(user.id))
        .using_app_db(&mut app_db)
        // This could in theory be done with `root_client` instead to save some
        // energy. It has been left as-is merely for consistency/convenience.
        .using_workspace_client(&mut workspace_client)
        .fetch_one()
        .await?;

    let target_user = if let Some(target_user) = User::with_email(&form.email)
        .fetch_optional(&mut app_db)
        .await?
    {
        target_user
    } else {
        User::upsert()
            .email(&form.email)
            .execute(&mut app_db)
            .await?
    };
    let mut root_client = pooler
        .acquire_for(workspace_id, RoleAssignment::Root)
        .await?;
    root_client
        .ensure_role(&format!(
            "{ROLE_PREFIX_USER}{id}",
            id = target_user.id.simple()
        ))
        .await?;
    let db_name = PgDatabase::current()
        .fetch_one(&mut root_client)
        .await?
        .datname;
    query(&format!(
        "grant connect on database {db_name_esc} to {rolname} with grant option",
        db_name_esc = escape_identifier(&db_name),
        rolname = escape_identifier(&format!(
            "{ROLE_PREFIX_USER}{user_id}",
            user_id = target_user.id.simple()
        ))
    ))
    .execute(root_client.get_conn())
    .await?;
    query(&format!(
        "grant usage, create on schema phono to {rolname} with grant option",
        rolname = escape_identifier(&format!(
            "{ROLE_PREFIX_USER}{user_id}",
            user_id = target_user.id.simple()
        ))
    ))
    .execute(root_client.get_conn())
    .await?;
    WorkspaceMembership::upsert()
        .workspace_id(workspace_id)
        .user_id(target_user.id)
        .execute(&mut app_db)
        .await?;

    Ok(navigator
        .workspace_page()
        .workspace_id(workspace_id)
        .suffix("settings/")
        .build()?
        .redirect_to())
}
