use axum::extract::{Path, Query, State};
use axum::Json;
use std::sync::Arc;

use crate::model::processing::note::NoteModel;
use crate::model::PackingContext;
use magnetar_sdk::endpoints::note::{GetNoteById, NoteByIdReq};
use magnetar_sdk::endpoints::{Req, Res};

use crate::service::MagnetarService;
use crate::web::auth::MaybeUser;
use crate::web::{ApiError, ObjectNotFound};

#[tracing::instrument(err, skip_all)]
pub async fn handle_note(
    Path(id): Path<String>,
    Query(NoteByIdReq {
        context,
        attachments,
    }): Query<Req<GetNoteById>>,
    State(service): State<Arc<MagnetarService>>,
    MaybeUser(self_user): MaybeUser,
) -> Result<Json<Res<GetNoteById>>, ApiError> {
    let ctx = PackingContext::new(service, self_user.clone()).await?;
    let note = NoteModel {
        attachments: attachments.unwrap_or_default(),
        with_context: context.unwrap_or_default(),
    }
    .fetch_single(&ctx, &id)
    .await?
    .ok_or(ObjectNotFound(id))?;

    Ok(Json(note))
}
