use axum::{
    debug_handler,
    extract::{Path, State},
    response::Response,
};
use phono_models::accessors::{Accessor as _, Actor, workspace::WorkspaceAccessor};
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 {
    name: String,
}

/// HTTP POST handler for updating a workspace's name.
#[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(FormBody { name }): ValidatedForm<FormBody>,
) -> Result<Response, AppError> {
    let mut workspace_client = pooler
        .acquire_for(workspace_id, RoleAssignment::User(user.id))
        .await?;

    // For auth only.
    // TODO: Limit access to workspace "owners" or equivalent.
    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?;

    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())
}
