use axum::{
    debug_handler,
    extract::{Path, State},
    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 phono_models::{
    accessors::{Accessor, Actor, portal::PortalAccessor},
    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,
    workspace_pooler::{RoleAssignment, WorkspacePooler},
};

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

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

/// HTTP POST handler for applying a filter to a portal's table viewer.
///
/// This handler expects 3 path parameters with the structure described by
/// [`PathParams`].
#[debug_handler(state = crate::app::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>,
    Form(FormBody { filter }): Form<FormBody>,
) -> Result<Response, AppError> {
    // FIXME: csrf

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

    let portal = PortalAccessor::new()
        .id(portal_id)
        .as_actor(Actor::User(user.id))
        .verify_workspace_id(workspace_id)
        .verify_rel_oid(Oid(rel_oid))
        .verify_rel_ownership()
        .using_app_db(&mut app_db)
        .using_workspace_client(&mut workspace_client)
        .fetch_one()
        .await?;

    Portal::update()
        .id(portal.id)
        .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())
}
