use axum::{
    extract::{Path, State},
    response::IntoResponse,
};
use interim_pgtypes::escape_identifier;
use serde::Deserialize;
use sqlx::query;
use uuid::Uuid;

use crate::{
    errors::AppError,
    navigator::{Navigator, NavigatorPage as _},
    roles::{
        ROLE_PREFIX_TABLE_OWNER, ROLE_PREFIX_TABLE_READER, ROLE_PREFIX_TABLE_WRITER,
        ROLE_PREFIX_USER,
    },
    user::CurrentUser,
    workspace_pooler::{RoleAssignment, WorkspacePooler},
    workspace_utils::PHONO_TABLE_NAMESPACE,
};

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

/// HTTP POST handler for creating a managed Postgres table within a workspace
/// database. Upon success, it redirects the client back to the workspace
/// homepage, which is expected to display a list of available tables including
/// the newly created one.
///
/// This handler expects 1 path parameter named `workspace_id` which should
/// deserialize to a UUID.
pub(super) async fn post(
    State(mut pooler): State<WorkspacePooler>,
    CurrentUser(user): CurrentUser,
    navigator: Navigator,
    Path(PathParams { workspace_id }): Path<PathParams>,
) -> Result<impl IntoResponse, AppError> {
    // FIXME: CSRF, Check workspace authorization.

    const NAME_LEN_WORDS: usize = 3;
    let table_name = interim_namegen::default_generator()
        .with_separator('_')
        .generate_name(NAME_LEN_WORDS);

    let mut root_client = pooler
        // FIXME: Should this be scoped down to the unprivileged role after
        // setting up the table owner?
        .acquire_for(workspace_id, RoleAssignment::Root)
        .await?;

    let user_rolname = format!("{ROLE_PREFIX_USER}{uid}", uid = user.id.simple());
    let rolname_uuid = Uuid::new_v4().simple();
    let rolname_table_owner = format!("{ROLE_PREFIX_TABLE_OWNER}{rolname_uuid}");
    let rolname_table_reader = format!("{ROLE_PREFIX_TABLE_READER}{rolname_uuid}");
    let rolname_table_writer = format!("{ROLE_PREFIX_TABLE_WRITER}{rolname_uuid}");
    for rolname in [
        &rolname_table_owner,
        &rolname_table_reader,
        &rolname_table_writer,
    ] {
        query(&format!("create role {0}", escape_identifier(rolname)))
            .execute(root_client.get_conn())
            .await?;
        query(&format!(
            "grant {0} to {1} with admin option",
            escape_identifier(rolname),
            escape_identifier(&user_rolname)
        ))
        .execute(root_client.get_conn())
        .await?;
    }

    query(&format!(
        r#"
create table {0}.{1} (
    _id uuid primary key not null default uuidv7(),
    _created_by text default current_user,
    _created_at timestamptz not null default now()
)
"#,
        escape_identifier(PHONO_TABLE_NAMESPACE),
        escape_identifier(&table_name),
    ))
    .execute(root_client.get_conn())
    .await?;
    query(&format!(
        "alter table {nsp}.{tbl} owner to {rol}",
        nsp = escape_identifier(PHONO_TABLE_NAMESPACE),
        tbl = escape_identifier(&table_name),
        rol = escape_identifier(&rolname_table_owner),
    ))
    .execute(root_client.get_conn())
    .await?;
    query(&format!(
        "grant select on {nsp}.{tbl} to {rol}",
        nsp = escape_identifier(PHONO_TABLE_NAMESPACE),
        tbl = escape_identifier(&table_name),
        rol = escape_identifier(&rolname_table_reader),
    ))
    .execute(root_client.get_conn())
    .await?;
    query(&format!(
        "grant delete, truncate on {nsp}.{tbl} to {rol}",
        nsp = escape_identifier(PHONO_TABLE_NAMESPACE),
        tbl = escape_identifier(&table_name),
        rol = escape_identifier(&rolname_table_writer),
    ))
    .execute(root_client.get_conn())
    .await?;

    Ok(navigator
        .workspace_page()
        .workspace_id(workspace_id)
        .build()?
        .redirect_to())
}
