use axum::{debug_handler, extract::Path, response::Response};
// [`axum_extra`]'s form extractor is preferred:
// https://docs.rs/axum-extra/0.10.1/axum_extra/extract/struct.Form.html#differences-from-axumextractform
use axum_extra::extract::Form;
use interim_models::{
    expression::PgExpressionAny,
    portal::Portal,
    workspace_user_perm::{self, WorkspaceUserPerm},
};
use serde::Deserialize;
use sqlx::postgres::types::Oid;
use uuid::Uuid;

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

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

#[derive(Debug, Deserialize)]
pub(super) struct FormBody {
    filter_expression: Option<String>,
}

/// HTTP POST handler for applying a [`PgExpressionAny`] filter to a portal's
/// table viewer.
///
/// This handler expects 3 path parameters with the structure described by
/// [`PathParams`].
#[debug_handler(state = App)]
pub(super) async fn post(
    AppDbConn(mut app_db): AppDbConn,
    CurrentUser(user): CurrentUser,
    navigator: Navigator,
    Path(PathParams {
        portal_id,
        rel_oid,
        workspace_id,
    }): Path<PathParams>,
    Form(form): Form<FormBody>,
) -> Result<Response, AppError> {
    // Check workspace authorization.
    let workspace_perms = WorkspaceUserPerm::belonging_to_user(user.id)
        .fetch_all(&mut app_db)
        .await?;
    if workspace_perms.iter().all(|p| {
        p.workspace_id != workspace_id || p.perm != workspace_user_perm::PermissionValue::Connect
    }) {
        return Err(forbidden!("access denied to workspace"));
    }
    // FIXME ensure workspace corresponds to rel/portal, and that user has
    // permission to access/alter both as needed.

    let portal = Portal::with_id(portal_id).fetch_one(&mut app_db).await?;
    let filter: Option<PgExpressionAny> =
        serde_json::from_str(&form.filter_expression.unwrap_or("null".to_owned()))?;
    Portal::update()
        .id(portal.id)
        .table_filter(filter)
        .build()?
        .execute(&mut app_db)
        .await?;

    Ok(navigator
        .portal_page()
        .workspace_id(workspace_id)
        .rel_oid(Oid(rel_oid))
        .portal_id(portal_id)
        .build()?
        .redirect_to())
}
