use axum::{debug_handler, extract::Path, response::Response};
use serde::Deserialize;
use sqlx::query;
use uuid::Uuid;
use validator::Validate;

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

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

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

/// HTTP POST handler for updating a workspace's name.
#[debug_handler(state = App)]
pub(super) async fn post(
    AppDbConn(mut app_db): AppDbConn,
    CurrentUser(_user): CurrentUser,
    navigator: Navigator,
    Path(PathParams { workspace_id }): Path<PathParams>,
    ValidatedForm(FormBody { name }): ValidatedForm<FormBody>,
) -> Result<Response, AppError> {
    // FIXME: Check workspace authorization.

    query!(
        "update workspaces set display_name = $1 where id = $2",
        name,
        workspace_id
    )
    .execute(app_db.get_conn())
    .await?;

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