use axum::extract::{Multipart, Path, Query, State};
use axum::http::StatusCode;
use axum::routing::{delete, get, post, put};
use axum::{Json, Router};
use serde::Deserialize;
use serde_json::json;
use uuid::Uuid;

use crate::api::pagination::PagedResponse;
use crate::app::AppState;
use crate::auth::extractor::{CurrentSessionUser, CurrentUser};
use crate::domain::manga::{MangaCard, MangaDetail, MangaPatch, NewManga};
use crate::domain::patch::Patch;
use crate::domain::tag::TagRef;
use crate::error::{AppError, AppResult};
use crate::repo;
use crate::storage::StorageError;
use crate::upload::{parse_image, UploadedImage};

pub fn routes() -> Router<AppState> {
    Router::new()
        .route("/mangas", get(list).post(create))
        .route("/mangas/:id", get(get_one).patch(update))
        .route("/mangas/:id/similar", get(list_similar))
        .route("/me/recommendations", get(list_recommendations))
        .route("/mangas/:id/cover", put(put_cover).delete(delete_cover))
        .route("/mangas/:id/tags", post(attach_tag))
        .route("/mangas/:id/tags/:tag_id", delete(detach_tag))
}

#[derive(Debug, Deserialize, Default)]
pub struct ListParams {
    #[serde(default)]
    pub search: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    /// Comma-separated UUIDs. AND across the list — every id must be
    /// attached to the manga for it to match.
    #[serde(default)]
    pub author_id: Option<String>,
    #[serde(default)]
    pub genre_id: Option<String>,
    #[serde(default)]
    pub tag_id: Option<String>,
    /// Comma-separated content warnings the manga must carry (AND).
    #[serde(default)]
    pub cw_include: Option<String>,
    /// Comma-separated content warnings the manga must NOT carry (any).
    #[serde(default)]
    pub cw_exclude: Option<String>,
    #[serde(default = "default_limit")]
    pub limit: i64,
    #[serde(default)]
    pub offset: i64,
    /// Sort field: `created`, `updated` (default), `title`, or `author`.
    /// Also accepts the legacy `recent` alias (== `created`). Anything
    /// else → 422.
    #[serde(default)]
    pub sort: Option<String>,
    /// `asc` or `desc`. Omitted → the field's natural default
    /// (dates `desc`, text `asc`). Anything else → 422.
    #[serde(default)]
    pub order: Option<String>,
}

fn default_limit() -> i64 {
    50
}

/// Parse the `sort` wire value into a [`repo::manga::SortField`]. Validation
/// and the legacy `recent` alias live here (not in serde) so unknown values
/// return the structured 422 envelope rather than axum's plain-text
/// `QueryRejection`, matching the rest of this handler's filters.
fn parse_sort(raw: Option<&str>) -> AppResult<repo::manga::SortField> {
    use repo::manga::SortField;
    match raw.map(str::trim) {
        None | Some("") | Some("updated") => Ok(SortField::Updated),
        // `recent` was the pre-0.88 name for "newest created first"; keep it
        // as an alias so existing bots/scripts don't break.
        Some("created") | Some("recent") => Ok(SortField::Created),
        Some("title") => Ok(SortField::Title),
        Some("author") => Ok(SortField::Author),
        Some(other) => Err(AppError::ValidationFailed {
            message: format!(
                "sort must be one of created, updated, title, author (got {other:?})"
            ),
            details: json!({ "sort": "invalid" }),
        }),
    }
}

/// Parse the `order` wire value. `None` means the client omitted it, so the
/// caller applies the field's natural default. An explicit unknown value → 422.
fn parse_order(raw: Option<&str>) -> AppResult<Option<repo::manga::SortOrder>> {
    use repo::manga::SortOrder;
    match raw.map(str::trim) {
        None | Some("") => Ok(None),
        Some("asc") => Ok(Some(SortOrder::Asc)),
        Some("desc") => Ok(Some(SortOrder::Desc)),
        Some(other) => Err(AppError::ValidationFailed {
            message: format!("order must be 'asc' or 'desc' (got {other:?})"),
            details: json!({ "order": "invalid" }),
        }),
    }
}

fn parse_uuid_csv(field: &str, raw: Option<&str>) -> AppResult<Vec<Uuid>> {
    let Some(raw) = raw else { return Ok(Vec::new()) };
    let mut out = Vec::new();
    for piece in raw.split(',') {
        let s = piece.trim();
        if s.is_empty() {
            continue;
        }
        let id = Uuid::parse_str(s).map_err(|_| AppError::ValidationFailed {
            message: format!("{field} contained an invalid UUID"),
            details: json!({ field: "comma-separated UUIDs" }),
        })?;
        out.push(id);
    }
    Ok(out)
}

async fn list(
    State(state): State<AppState>,
    Query(params): Query<ListParams>,
) -> AppResult<Json<PagedResponse<MangaCard>>> {
    let limit = params.limit.clamp(1, 200);
    let offset = params.offset.max(0);
    let status = match params.status.as_deref().map(str::trim) {
        None | Some("") => None,
        Some(s) => {
            if !repo::manga::STATUSES.contains(&s) {
                return Err(AppError::ValidationFailed {
                    message: "invalid status filter".into(),
                    details: json!({ "status": format!("must be one of {:?}", repo::manga::STATUSES) }),
                });
            }
            Some(s.to_string())
        }
    };
    let sort = parse_sort(params.sort.as_deref())?;
    // Omitted `order` falls back to the field's natural direction, so a bare
    // `?sort=title` reads A→Z just like the UI shows it.
    let order = parse_order(params.order.as_deref())?.unwrap_or_else(|| sort.default_order());
    let q = repo::manga::ListQuery {
        search: params.search.filter(|s| !s.trim().is_empty()),
        status,
        author_ids: parse_uuid_csv("author_id", params.author_id.as_deref())?,
        genre_ids: parse_uuid_csv("genre_id", params.genre_id.as_deref())?,
        tag_ids: parse_uuid_csv("tag_id", params.tag_id.as_deref())?,
        cw_include: crate::api::page_tags::parse_warnings_csv(params.cw_include.as_deref())?,
        cw_exclude: crate::api::page_tags::parse_warnings_csv(params.cw_exclude.as_deref())?,
        limit,
        offset,
        sort,
        order,
    };
    let (items, total) = repo::manga::list_cards(&state.db, &q).await?;
    Ok(Json(PagedResponse::with_optional_total(
        items, limit, offset, total,
    )))
}

async fn get_one(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
) -> AppResult<Json<MangaDetail>> {
    Ok(Json(repo::manga::get_detail(&state.db, id).await?))
}

/// How many similar mangas the recommendation section shows.
const SIMILAR_LIMIT: i64 = 5;

/// `GET /api/v1/mangas/:id/similar` — top-`SIMILAR_LIMIT` mangas ranked by
/// tag overlap with `:id`, as cards. Read-only and unauthenticated, like
/// `get_one`/`list`. Returns a plain `{ items: [...] }` object (not the
/// paginated envelope) since this is a fixed top-N, not a collection.
///
/// The `exists` check is load-bearing: `list_similar` returns an empty list
/// for both an untagged manga and a nonexistent id, so without it an unknown
/// id would 200 with `[]` instead of 404.
async fn list_similar(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
) -> AppResult<Json<serde_json::Value>> {
    if !repo::manga::exists(&state.db, id).await? {
        return Err(AppError::NotFound);
    }
    let items = repo::manga::list_similar(&state.db, id, SIMILAR_LIMIT).await?;
    Ok(Json(json!({ "items": items })))
}

const RECOMMENDATIONS_LIMIT: i64 = 12;

#[derive(Debug, Deserialize)]
pub struct RecommendationParams {
    #[serde(default)]
    pub limit: Option<i64>,
}

/// `GET /api/v1/me/recommendations` — content-based "Recommended for you",
/// ranked by tag overlap with the signed-in user's likes/bookmarks (minus
/// dislikes). Returns `{ "items": [...] }` (a fixed top-N, like `/similar`);
/// empty when the user has no taste signals yet.
async fn list_recommendations(
    State(state): State<AppState>,
    CurrentUser(user): CurrentUser,
    Query(params): Query<RecommendationParams>,
) -> AppResult<Json<serde_json::Value>> {
    let limit = params.limit.unwrap_or(RECOMMENDATIONS_LIMIT).clamp(1, 50);
    let items = repo::manga::list_recommendations(&state.db, user.id, limit).await?;
    Ok(Json(json!({ "items": items })))
}

/// `POST /api/v1/mangas` is multipart/form-data. Parts:
///
/// - `metadata` (required): JSON body matching `NewManga` — title, optional
///   status, optional authors (array of names), optional alt_titles
///   (array), optional description, optional genre_ids (array of UUIDs).
/// - `cover` (optional): image bytes. MIME is sniffed from magic bytes
///   (jpeg/png/webp/gif/avif); size capped at `upload.max_file_bytes`.
///
/// Anything else is ignored. Authors are upserted into the global
/// authors table (case-insensitive de-dup); genre_ids are validated
/// against the curated genres list.
async fn create(
    State(state): State<AppState>,
    CurrentUser(_user): CurrentUser,
    mut multipart: Multipart,
) -> AppResult<(StatusCode, Json<MangaDetail>)> {
    let mut metadata: Option<NewManga> = None;
    let mut cover: Option<UploadedImage> = None;

    while let Some(field) = next_field(&mut multipart).await? {
        match field.name() {
            Some("metadata") => {
                let bytes = read_field_bytes(field).await?;
                metadata = Some(parse_metadata_json(&bytes)?);
            }
            Some("cover") => {
                let bytes = read_field_bytes(field).await?.to_vec();
                cover = Some(parse_image(bytes, state.upload.max_file_bytes, "cover")?);
            }
            _ => continue,
        }
    }

    let metadata = metadata.ok_or_else(|| AppError::ValidationFailed {
        message: "metadata part is required".into(),
        details: json!({ "metadata": "required" }),
    })?;
    validate_new_manga(&metadata)?;
    validate_genre_ids(&state, &metadata.genre_ids).await?;

    let status = metadata
        .status
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .unwrap_or(repo::manga::DEFAULT_STATUS)
        .to_string();
    let alt_titles = normalize_alt_titles(metadata.alt_titles);
    let authors = normalize_string_list(metadata.authors);

    // Transactional create. If the cover put or any relation write
    // fails, the manga row and its relations are rolled back so a
    // half-uploaded cover doesn't leave a manga without one stuck
    // pointing at it. Bytes already written to storage on a rolled-back
    // transaction become orphans on disk — a future reaper can sweep
    // them; we prioritise DB consistency over storage tidiness here.
    let mut tx = state.db.begin().await?;
    let mut manga = repo::manga::create(
        &mut *tx,
        metadata.title.trim(),
        &status,
        metadata.description.as_deref(),
        &alt_titles,
        Some(_user.id),
    )
    .await?;

    let author_refs = repo::author::set_for_manga(&mut tx, manga.id, &authors).await?;
    repo::genre::set_for_manga(&mut tx, manga.id, &metadata.genre_ids).await?;

    if let Some(img) = cover {
        let key = format!("mangas/{}/cover.{}", manga.id, img.ext);
        state.storage.put(&key, &img.bytes).await?;
        repo::manga::set_cover_image_path(&mut *tx, manga.id, &key, img.bytes.len() as i64)
            .await?;
        manga.cover_image_path = Some(key);
    }

    tx.commit().await?;

    // Re-read so the genres list reflects the canonical sort order
    // and any future trigger-driven defaults.
    let detail = repo::manga::get_detail(&state.db, manga.id).await?;
    let _ = author_refs; // returned for free via detail
    Ok((StatusCode::CREATED, Json(detail)))
}

async fn update(
    State(state): State<AppState>,
    CurrentUser(user): CurrentUser,
    session: Option<CurrentSessionUser>,
    Path(id): Path<Uuid>,
    Json(patch): Json<MangaPatch>,
) -> AppResult<Json<MangaDetail>> {
    if !repo::manga::exists(&state.db, id).await? {
        return Err(AppError::NotFound);
    }
    require_can_edit(&state, id, user.id, admin_via_session(&session)).await?;

    if let Some(ref status) = patch.status {
        let trimmed = status.trim();
        if !repo::manga::STATUSES.contains(&trimmed) {
            return Err(AppError::ValidationFailed {
                message: "invalid status".into(),
                details: json!({ "status": format!("must be one of {:?}", repo::manga::STATUSES) }),
            });
        }
    }
    if let Some(ref title) = patch.title {
        if title.trim().is_empty() {
            return Err(AppError::ValidationFailed {
                message: "title cannot be blank".into(),
                details: json!({ "title": "non-empty" }),
            });
        }
    }
    if let Some(ref ids) = patch.genre_ids {
        validate_genre_ids(&state, ids).await?;
    }

    let alt_titles_owned: Option<Vec<String>> =
        patch.alt_titles.map(normalize_alt_titles);
    let authors_owned: Option<Vec<String>> =
        patch.authors.map(normalize_string_list);

    let description_provided = patch.description.is_provided();
    let description_value: Option<&str> = match &patch.description {
        Patch::Set(s) => Some(s.as_str()),
        Patch::Clear | Patch::Unchanged => None,
    };

    let mut tx = state.db.begin().await?;
    let _updated = repo::manga::update_basics(
        &mut tx,
        id,
        patch.title.as_deref().map(str::trim),
        patch.status.as_deref().map(str::trim),
        description_provided,
        description_value,
        alt_titles_owned.as_deref(),
    )
    .await?;
    if let Some(ref names) = authors_owned {
        repo::author::set_for_manga(&mut tx, id, names).await?;
    }
    if let Some(ref ids) = patch.genre_ids {
        repo::genre::set_for_manga(&mut tx, id, ids).await?;
    }
    tx.commit().await?;

    Ok(Json(repo::manga::get_detail(&state.db, id).await?))
}

/// `PUT /api/v1/mangas/:id/cover` is multipart/form-data with a single
/// required `cover` part containing image bytes. MIME is sniffed by
/// magic bytes (jpeg/png/webp/gif/avif); filename and Content-Type from
/// the client are ignored. Replaces any existing cover, deleting the
/// previous blob if its extension differs. Returns the refreshed
/// `MangaDetail`.
async fn put_cover(
    State(state): State<AppState>,
    CurrentUser(user): CurrentUser,
    session: Option<CurrentSessionUser>,
    Path(id): Path<Uuid>,
    mut multipart: Multipart,
) -> AppResult<Json<MangaDetail>> {
    if !repo::manga::exists(&state.db, id).await? {
        return Err(AppError::NotFound);
    }
    require_can_edit(&state, id, user.id, admin_via_session(&session)).await?;

    let mut cover: Option<UploadedImage> = None;
    while let Some(field) = next_field(&mut multipart).await? {
        if field.name() == Some("cover") {
            let bytes = read_field_bytes(field).await?.to_vec();
            cover = Some(parse_image(bytes, state.upload.max_file_bytes, "cover")?);
        }
    }
    let img = cover.ok_or_else(|| AppError::ValidationFailed {
        message: "cover part is required".into(),
        details: json!({ "cover": "required" }),
    })?;

    // Read the old key BEFORE writing so we can clean up an orphan if
    // the extension changed (e.g., .png → .jpg). Same-extension is a
    // `put` overwrite — no delete needed.
    let old_key = repo::manga::get(&state.db, id).await?.cover_image_path;
    let new_key = format!("mangas/{}/cover.{}", id, img.ext);
    state.storage.put(&new_key, &img.bytes).await?;

    if let Some(prev) = old_key.as_deref() {
        if prev != new_key {
            // Swallow NotFound — AppError maps it to a client 404,
            // which would be wrong here. The DB row can outlive a
            // manually-deleted blob.
            match state.storage.delete(prev).await {
                Ok(()) | Err(StorageError::NotFound) => {}
                Err(e) => return Err(e.into()),
            }
        }
    }

    repo::manga::set_cover_image_path(&state.db, id, &new_key, img.bytes.len() as i64).await?;
    Ok(Json(repo::manga::get_detail(&state.db, id).await?))
}

/// `DELETE /api/v1/mangas/:id/cover` clears `cover_image_path` and
/// removes the blob. Idempotent: removing a non-existent cover succeeds
/// with the unchanged detail.
async fn delete_cover(
    State(state): State<AppState>,
    CurrentUser(user): CurrentUser,
    session: Option<CurrentSessionUser>,
    Path(id): Path<Uuid>,
) -> AppResult<Json<MangaDetail>> {
    if !repo::manga::exists(&state.db, id).await? {
        return Err(AppError::NotFound);
    }
    require_can_edit(&state, id, user.id, admin_via_session(&session)).await?;
    if let Some(key) = repo::manga::get(&state.db, id).await?.cover_image_path {
        match state.storage.delete(&key).await {
            Ok(()) | Err(StorageError::NotFound) => {}
            Err(e) => return Err(e.into()),
        }
        repo::manga::clear_cover_image_path(&state.db, id).await?;
    }
    Ok(Json(repo::manga::get_detail(&state.db, id).await?))
}

#[derive(Debug, Deserialize)]
pub struct AttachTagBody {
    pub name: String,
}

async fn attach_tag(
    State(state): State<AppState>,
    CurrentUser(user): CurrentUser,
    Path(id): Path<Uuid>,
    Json(body): Json<AttachTagBody>,
) -> AppResult<(StatusCode, Json<TagRef>)> {
    validate_tag_name(&body.name)?;
    if !repo::manga::exists(&state.db, id).await? {
        return Err(AppError::NotFound);
    }
    let outcome = repo::tag::attach_to_manga(&state.db, id, &body.name, user.id).await?;
    let status = if outcome.created_attachment {
        StatusCode::CREATED
    } else {
        StatusCode::OK
    };
    // `added_by` reflects who currently owns the attachment — which is
    // the first attacher, not the caller. Look it up so the response
    // matches what subsequent list_for_manga reads will show.
    let added_by = repo::tag::find_attacher(&state.db, id, outcome.tag.id)
        .await?
        .flatten();
    Ok((
        status,
        Json(TagRef {
            id: outcome.tag.id,
            name: outcome.tag.name,
            added_by,
        }),
    ))
}

async fn detach_tag(
    State(state): State<AppState>,
    CurrentUser(user): CurrentUser,
    Path((manga_id, tag_id)): Path<(Uuid, Uuid)>,
) -> AppResult<StatusCode> {
    match repo::tag::find_attacher(&state.db, manga_id, tag_id).await? {
        None => Err(AppError::NotFound),
        Some(added_by) => {
            // `added_by` is None if the attaching user was deleted; in
            // that case nobody owns it, so we refuse rather than let
            // any user clear orphan tags (an admin role can do that
            // later).
            if added_by != Some(user.id) {
                return Err(AppError::Forbidden);
            }
            repo::tag::detach(&state.db, manga_id, tag_id).await?;
            Ok(StatusCode::NO_CONTENT)
        }
    }
}

/// Request-side validation for `POST /mangas/:id/tags` body. Mirrors
/// the repo-level cap in `repo::tag::upsert_by_name` (max 64 chars
/// after trim) but surfaces the failure at the handler boundary with
/// the same envelope shape other validations use.
fn validate_tag_name(name: &str) -> AppResult<()> {
    let trimmed = name.trim();
    if trimmed.is_empty() {
        return Err(AppError::ValidationFailed {
            message: "tag name cannot be empty".into(),
            details: json!({ "name": "required" }),
        });
    }
    if trimmed.chars().count() > 64 {
        return Err(AppError::ValidationFailed {
            message: "tag name too long".into(),
            details: json!({ "name": "max 64 characters" }),
        });
    }
    Ok(())
}

fn validate_new_manga(input: &NewManga) -> AppResult<()> {
    if input.title.trim().is_empty() {
        return Err(AppError::ValidationFailed {
            message: "title is required".into(),
            details: json!({ "title": "required" }),
        });
    }
    if let Some(ref status) = input.status {
        let trimmed = status.trim();
        if !trimmed.is_empty() && !repo::manga::STATUSES.contains(&trimmed) {
            return Err(AppError::ValidationFailed {
                message: "invalid status".into(),
                details: json!({ "status": format!("must be one of {:?}", repo::manga::STATUSES) }),
            });
        }
    }
    Ok(())
}

/// Authorisation gate for manga mutations. The manga is assumed to
/// exist (the caller runs [`repo::manga::exists`] first so a missing id
/// surfaces as `NotFound`, not `Forbidden`).
///
/// Rule: a non-NULL `uploaded_by` must match the current user, OR the
/// caller is an admin **via a session cookie**. Rows with
/// `uploaded_by IS NULL` (crawler-imported + legacy pre-0011) are
/// admin-via-session-only.
///
/// Why "via session": [`crate::auth::extractor`] documents that admin
/// authority is unreachable via bearer tokens — a leaked bot token
/// must not yield admin powers. Keep that invariant by reading the
/// `is_admin_session` flag from the optional `CurrentSessionUser`
/// extractor (`None` ⇒ caller authenticated via bearer ⇒ admin path
/// is closed) rather than from `User.is_admin` (which is true whichever
/// way the user authenticated).
///
/// Why NULL is admin-only: every crawler row has NULL `uploaded_by`
/// (see `repo::crawler::upsert_manga`). The earlier "any signed-in
/// user can edit a NULL row" rule meant `register → PATCH
/// /api/v1/mangas/<id>` rewrote the catalog for free, and
/// `delete_cover` removed blobs from `storage`.
///
/// Returns `Forbidden` (not `NotFound`) on owner mismatch — mangas
/// are listable via `GET /mangas`, so existence isn't a secret and
/// the more accurate 403 is fine. This deliberately differs from
/// `repo::collection::require_owner`, which collapses both states to
/// `NotFound` because collections are private to a user and existence
/// itself is information worth hiding from non-owners.
async fn require_can_edit(
    state: &AppState,
    manga_id: Uuid,
    user_id: Uuid,
    is_admin_session: bool,
) -> AppResult<()> {
    match repo::manga::uploaded_by(&state.db, manga_id).await? {
        Some(owner) if owner == user_id => Ok(()),
        Some(_) if is_admin_session => Ok(()),
        Some(_) => Err(AppError::Forbidden),
        None if is_admin_session => Ok(()),
        None => Err(AppError::Forbidden),
    }
}

/// True iff the caller authenticated via session cookie AND is an admin.
/// Used to gate the admin-only branches of [`require_can_edit`]. The
/// `Option<CurrentSessionUser>` extractor returns `None` on a bearer-only
/// request, so admin authority over bot tokens never composes here.
fn admin_via_session(session: &Option<CurrentSessionUser>) -> bool {
    session
        .as_ref()
        .map(|CurrentSessionUser(u)| u.is_admin)
        .unwrap_or(false)
}

async fn validate_genre_ids(state: &AppState, ids: &[Uuid]) -> AppResult<()> {
    if ids.is_empty() {
        return Ok(());
    }
    // Dedup before counting — Postgres' `id = ANY(...)` is set-based,
    // so a request with `[g1, g1]` would match one row and trip the
    // "unknown id" branch even though the only id is real. The DB-side
    // insert path also dedupes via `ON CONFLICT DO NOTHING`, so we
    // simply silently accept duplicates from the client.
    let unique: std::collections::HashSet<Uuid> = ids.iter().copied().collect();
    let (matched,): (i64,) =
        sqlx::query_as("SELECT count(*) FROM genres WHERE id = ANY($1)")
            .bind(ids)
            .fetch_one(&state.db)
            .await?;
    if (matched as usize) != unique.len() {
        return Err(AppError::ValidationFailed {
            message: "unknown genre id".into(),
            details: json!({ "genre_ids": "all ids must reference an existing genre" }),
        });
    }
    Ok(())
}

fn normalize_alt_titles(raw: Vec<String>) -> Vec<String> {
    let mut out = Vec::with_capacity(raw.len());
    for t in raw {
        let trimmed = t.trim();
        if trimmed.is_empty() {
            continue;
        }
        let s = trimmed.to_string();
        if !out.contains(&s) {
            out.push(s);
        }
    }
    out
}

fn normalize_string_list(raw: Vec<String>) -> Vec<String> {
    let mut out = Vec::with_capacity(raw.len());
    for s in raw {
        let trimmed = s.trim();
        if trimmed.is_empty() {
            continue;
        }
        // Case-insensitive de-dup so ["Miura", "miura"] becomes one entry.
        if !out
            .iter()
            .any(|existing: &String| existing.eq_ignore_ascii_case(trimmed))
        {
            out.push(trimmed.to_string());
        }
    }
    out
}

fn parse_metadata_json(bytes: &[u8]) -> AppResult<NewManga> {
    serde_json::from_slice(bytes).map_err(|e| AppError::ValidationFailed {
        message: "metadata is not valid JSON".into(),
        details: json!({ "metadata": e.to_string() }),
    })
}

pub(crate) async fn next_field(
    multipart: &mut Multipart,
) -> AppResult<Option<axum::extract::multipart::Field<'_>>> {
    multipart
        .next_field()
        .await
        .map_err(map_multipart_error)
}

pub(crate) async fn read_field_bytes(
    field: axum::extract::multipart::Field<'_>,
) -> AppResult<axum::body::Bytes> {
    field.bytes().await.map_err(map_multipart_error)
}

pub(crate) fn map_multipart_error(e: axum::extract::multipart::MultipartError) -> AppError {
    let status = e.status();
    if status == StatusCode::PAYLOAD_TOO_LARGE {
        AppError::PayloadTooLarge("upload exceeds the request size limit".into())
    } else {
        AppError::InvalidInput(format!("multipart parse error: {e}"))
    }
}
