use axum::{
    debug_handler,
    extract::{Path, State},
    response::Response,
};
use interim_models::portal::{Portal, RE_PORTAL_NAME};
use interim_pgtypes::pg_class::PgClass;
use serde::Deserialize;
use sqlx::postgres::types::Oid;
use uuid::Uuid;
use validator::Validate;

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

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

#[derive(Debug, Deserialize, Validate)]
pub(super) struct FormBody {
    #[validate(regex(path = *RE_PORTAL_NAME))]
    name: String,
}

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

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

    let rel = PgClass::with_oid(Oid(rel_oid))
        .fetch_one(&mut workspace_client)
        .await?;
    // FIXME ensure that user has ownership of the table.

    let portal = Portal::with_id(portal_id).fetch_one(&mut app_db).await?;

    Portal::update()
        .id(portal_id)
        .name(name)
        .build()?
        .execute(&mut app_db)
        .await?;

    Ok(navigator
        .portal_page()
        .workspace_id(workspace_id)
        .rel_oid(Oid(rel_oid))
        .portal_id(portal_id)
        .suffix("settings/")
        .build()?
        .redirect_to())
}
