use axum::{
    debug_handler,
    extract::{Path, State},
    response::Response,
};
use phono_models::{
    accessors::{Accessor as _, Actor, portal::PortalAccessor},
    field::Field,
};
use serde::Deserialize;
use sqlx::postgres::types::Oid;
use uuid::Uuid;
use validator::Validate;

use crate::{
    app::AppDbConn,
    errors::AppError,
    extractors::ValidatedForm,
    navigator::{Navigator, NavigatorPage},
    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, Validate)]
pub(super) struct FormBody {
    field_id: Uuid,
    #[validate(range(min = 0.0))]
    ordinality: f64,
}

/// HTTP POST handler for updating the ordinal position of an existing
/// [`Field`]. This is distinct from `./update-field`, because it is initiated
/// in the UI by a "drag" interaction. It may make sense to fold this into the
/// aforementioned endpoint later, if it is modified to handle partial updates.
///
/// This handler expects 3 path parameters with the structure described by
/// [`PathParams`].
#[debug_handler(state = crate::app::App)]
pub(super) async fn post(
    State(mut pooler): State<WorkspacePooler>,
    AppDbConn(mut app_db): AppDbConn,
    CurrentUser(user): CurrentUser,
    navigator: Navigator,
    Path(PathParams {
        portal_id,
        rel_oid,
        workspace_id,
    }): Path<PathParams>,
    ValidatedForm(FormBody {
        field_id,
        ordinality,
    }): ValidatedForm<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?;

    // 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)
        .ordinality(ordinality)
        .build()?
        .execute(&mut app_db)
        .await?;

    // TODO: Redirect with subfilter query intact.
    Ok(navigator
        .portal_page()
        .workspace_id(workspace_id)
        .rel_oid(Oid(rel_oid))
        .portal_id(portal.id)
        .build()?
        .redirect_to())
}
