use axum::{
    debug_handler,
    extract::{Path, State},
    response::Response,
};
use phono_models::{
    accessors::{Accessor, Actor, portal::PortalAccessor},
    field::Field,
    presentation::Presentation,
};
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},
    presentation_form::PresentationForm,
    user::CurrentUser,
    workspace_pooler::WorkspacePooler,
};

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

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

    presentation_tag: String,

    #[serde(default)]
    dropdown_option_colors: Vec<String>,

    #[serde(default)]
    dropdown_option_values: Vec<String>,

    #[serde(default)]
    text_input_mode: String,

    #[serde(default)]
    timestamp_format: String,
}

impl From<FormBody> for PresentationForm {
    fn from(value: FormBody) -> Self {
        Self {
            presentation_tag: value.presentation_tag,
            dropdown_option_colors: value.dropdown_option_colors,
            dropdown_option_values: value.dropdown_option_values,
            text_input_mode: value.text_input_mode,
            timestamp_format: value.timestamp_format,
        }
    }
}

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

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

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

    Field::update()
        .id(form.field_id)
        .table_label(if form.table_label.is_empty() {
            None
        } else {
            Some(form.table_label.clone())
        })
        .presentation(Presentation::try_from(Into::<PresentationForm>::into(
            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())
}
