use axum::{debug_handler, extract::Path, response::Response};
use interim_models::{field::Field, presentation::Presentation};
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},
    presentation_form::PresentationForm,
    user::CurrentUser,
};

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

#[derive(Debug, Deserialize, Validate)]
pub(super) struct FormBody {
    field_id: Uuid,
    table_label: String,

    #[serde(flatten)]
    presentation_form: PresentationForm,
}

/// HTTP POST handler for updating an existing [`Field`].
///
/// 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>,
    ValidatedForm(FormBody {
        field_id,
        table_label,
        presentation_form,
    }): ValidatedForm<FormBody>,
) -> Result<Response, AppError> {
    // FIXME CSRF

    // FIXME ensure workspace corresponds to rel/portal, and that user has
    // permission to access/alter both as needed.

    // Ensure field exists and belongs to portal.
    Field::belonging_to_portal(portal_id)
        .with_id(field_id)
        .fetch_one(&mut app_db)
        .await?;

    Field::update()
        .id(field_id)
        .table_label(if table_label.is_empty() {
            None
        } else {
            Some(table_label)
        })
        .presentation(Presentation::try_from(presentation_form)?)
        .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())
}
