use axum::{extract::Path, response::IntoResponse};
use phono_models::portal::Portal;
use serde::Deserialize;
use sqlx::postgres::types::Oid;
use uuid::Uuid;

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

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

/// HTTP POST handler for creating a [`Portal`] for an existing backing database
/// table. Upon success, it redirects the client to the portal's table viewer.
///
/// This handler expects 2 path parameters, named `workspace_id`, which should
/// deserialize to a UUID, and `rel_oid`, which should deserialize to a u32.
pub(super) async fn post(
    CurrentUser(_user): CurrentUser,
    navigator: Navigator,
    AppDbConn(mut app_db): AppDbConn,
    Path(PathParams {
        rel_oid,
        workspace_id,
    }): Path<PathParams>,
) -> Result<impl IntoResponse, AppError> {
    // FIXME: Check workspace authorization.

    Portal::insert()
        .workspace_id(workspace_id)
        .name("Untitled".to_owned())
        .class_oid(Oid(rel_oid))
        .build()?
        .execute(&mut app_db)
        .await?;

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