use std::iter::zip;

use axum::{debug_handler, extract::Path, response::Response};
// [`axum_extra`]'s form extractor is required to support repeated keys:
// 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::{
    form_transition::{self, FormTransition},
    workspace_user_perm::{self, WorkspaceUserPerm},
};
use serde::Deserialize;
use sqlx::postgres::types::Oid;
use uuid::Uuid;

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

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

#[derive(Clone, Debug, Deserialize)]
pub(super) struct FormBody {
    dest: Vec<Uuid>,
    condition: Vec<String>,
}

/// HTTP POST handler for setting form transitions for a [`Portal`]. The form
/// body is expected to be an HTTP form encoded with a list of inputs named
/// `"dest"` and `"condition"`, where `"dest"` encodes a portal ID and
/// `"condition"` is JSON deserializing to [`PgExpressionAny`].
///
/// Upon success, the client is redirected back to the portal's form editor
/// page.
#[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.
    // FIXME CSRF

    let replacements = zip(form.dest, form.condition)
        .map(|(dest_id, condition)| {
            Ok(form_transition::Replacement {
                dest_id,
                condition: serde_json::from_str(&condition)?,
            })
        })
        .collect::<Result<Vec<_>, serde_json::Error>>()
        .map_err(|err| bad_request!("unable to deserialize condition: {err}"))?;

    FormTransition::replace_for_portal(portal_id)
        .replacements(replacements)
        .build()?
        .execute(&mut app_db)
        .await?;

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