38.4 KiB · text History 7d724b1
use axum::{
    extract::{Form, Path, Query, State},
    http::{HeaderMap, StatusCode},
    response::{Html, IntoResponse, Redirect},
};
use axum_htmx::HxRequest;
use chrono::Utc;
use minijinja::context;
use sea_orm::*;
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};
use tracing::error;
use uuid::Uuid;

/// A given viewer bumps a topic's view count at most once per this window.
const VIEW_WINDOW: Duration = Duration::from_secs(600); // 10 minutes

/// Topic-list ordering. Pinned topics always sort first; this controls the
/// order among the rest (and among pinned).
#[derive(Clone, Copy, PartialEq, Eq)]
enum TopicSort {
    Latest,
    Top,
    Bottom,
    Hot,
}

impl TopicSort {
    fn parse(s: &str) -> Option<Self> {
        match s {
            "latest" => Some(Self::Latest),
            "top" => Some(Self::Top),
            "bottom" => Some(Self::Bottom),
            "hot" => Some(Self::Hot),
            _ => None,
        }
    }

    fn as_str(self) -> &'static str {
        match self {
            Self::Latest => "latest",
            Self::Top => "top",
            Self::Bottom => "bottom",
            Self::Hot => "hot",
        }
    }
}

/// "Hotness": engagement (posts) decayed by how long since the last reply.
/// Higher = hotter.
fn hot_score(t: &topics::Model, now: chrono::DateTime<chrono::Utc>) -> f64 {
    let hours = (now - t.bumped_at.with_timezone(&chrono::Utc))
        .num_seconds()
        .max(0) as f64
        / 3600.0;
    (t.posts_count.max(0) as f64) / (hours + 2.0).powf(1.5)
}

/// Sort topics in place: pinned first, then by the chosen order.
fn sort_topics(rows: &mut [(topics::Model, Option<users::Model>)], sort: TopicSort) {
    let now = Utc::now();
    rows.sort_by(|(a, _), (b, _)| {
        b.is_pinned.cmp(&a.is_pinned).then_with(|| match sort {
            TopicSort::Latest => b.bumped_at.cmp(&a.bumped_at),
            TopicSort::Top => b.views.cmp(&a.views).then(b.bumped_at.cmp(&a.bumped_at)),
            TopicSort::Bottom => a.views.cmp(&b.views).then(b.bumped_at.cmp(&a.bumped_at)),
            TopicSort::Hot => hot_score(b, now)
                .partial_cmp(&hot_score(a, now))
                .unwrap_or(std::cmp::Ordering::Equal),
        })
    });
}

/// Best-effort client IP for throttling anonymous viewers (proxy headers, else
/// a shared fallback bucket).
fn client_ip(headers: &HeaderMap) -> String {
    headers
        .get("x-forwarded-for")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.split(',').next().unwrap_or(s).trim().to_string())
        .or_else(|| {
            headers
                .get("x-real-ip")
                .and_then(|v| v.to_str().ok())
                .map(|s| s.trim().to_string())
        })
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "anon".to_string())
}

use crate::category_tree::{color_widget_css, CategoryTree, Viewer};
use crate::entities::{
    bookmarks, categories, category_watches, posts, tags, topic_tags, topics, users,
};
use crate::handlers::posts::record_revision;
use crate::handlers::reactions::{active_reaction_types, reaction_views_for_posts, ReactionView};
use crate::markdown;
use crate::middleware::UserContext;
use crate::timeutil::{abs, rel};
use crate::AppState;

fn ise<E: std::fmt::Display>(ctx: &'static str) -> impl Fn(E) -> StatusCode {
    move |e| {
        error!(error = %e, "{ctx}");
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

#[derive(Serialize)]
struct SubRow {
    name: String,
    slug: String,
    depth: i32,
    topic_count: u64,
    /// CSS `background` for the lineage widget (full circle / halves / thirds).
    widget_bg: String,
}

#[derive(Serialize)]
struct CategoryRow {
    name: String,
    slug: String,
    description: Option<String>,
    topic_count: u64,
    widget_bg: String,
    subcategories: Vec<SubRow>,
}

#[derive(Serialize)]
struct Crumb {
    name: String,
    slug: String,
}

#[derive(Serialize)]
struct ChipRow {
    name: String,
    slug: String,
    widget_bg: String,
}

#[derive(Serialize, Clone)]
pub struct TagChip {
    pub name: String,
    pub slug: String,
}

#[derive(Serialize)]
pub struct TopicRow {
    id: Uuid,
    title: String,
    is_pinned: bool,
    is_closed: bool,
    posts_count: i32,
    views: i32,
    bumped_at: String,
    bumped_at_abs: String,
    author: String,
    author_id: Uuid,
    author_has_avatar: bool,
    /// The topic's own category widget (lineage circle), shown to the left of
    /// the title; links to that category.
    cat_widget_bg: String,
    cat_name: String,
    cat_slug: String,
    tags: Vec<TagChip>,
}

/// Read-capability of an optional viewer.
pub fn viewer_of(uc: &Option<UserContext>) -> Viewer {
    Viewer {
        level: uc.as_ref().map(|c| c.user.trust_level),
        staff: uc.as_ref().is_some_and(|c| c.user.is_staff),
    }
}

fn viewer_user(u: &UserContext) -> Viewer {
    Viewer {
        level: Some(u.user.trust_level),
        staff: u.user.is_staff,
    }
}

/// 404 unless the viewer can read `category_id`.
pub async fn ensure_category_visible(
    state: &AppState,
    category_id: Uuid,
    uc: &Option<UserContext>,
) -> Result<(), StatusCode> {
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    if tree.can_view(category_id, viewer_of(uc)) {
        Ok(())
    } else {
        Err(StatusCode::NOT_FOUND)
    }
}

/// 404 unless the viewer can read the topic's category.
pub async fn ensure_topic_visible(
    state: &AppState,
    topic_id: Uuid,
    uc: &Option<UserContext>,
) -> Result<(), StatusCode> {
    let topic = topics::Entity::find_by_id(topic_id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic for visibility"))?
        .ok_or(StatusCode::NOT_FOUND)?;
    ensure_category_visible(state, topic.category_id, uc).await
}

/// Slugify a tag name (lowercase alphanumerics; runs of other chars → `-`).
fn tag_slug(s: &str) -> String {
    let mut out = String::new();
    let mut dash = false;
    for ch in s.trim().chars() {
        if ch.is_alphanumeric() {
            out.extend(ch.to_lowercase());
            dash = false;
        } else if !out.is_empty() && !dash {
            out.push('-');
            dash = true;
        }
    }
    while out.ends_with('-') {
        out.pop();
    }
    out
}

/// Tag chips for a single topic.
async fn tags_for_topic(state: &AppState, topic_id: Uuid) -> Result<Vec<TagChip>, StatusCode> {
    Ok(topic_tags::Entity::find()
        .filter(topic_tags::Column::TopicId.eq(topic_id))
        .find_also_related(tags::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load topic tags"))?
        .into_iter()
        .filter_map(|(_, t)| t.map(|t| TagChip { name: t.name, slug: t.slug }))
        .collect())
}

/// Maximum number of tags on one topic.
const MAX_TAGS: usize = 5;

/// Parse a comma-separated tag list into `(name, slug)` pairs: trimmed,
/// slugified, deduplicated by slug, at most [`MAX_TAGS`].
fn parse_tag_list(raw: &str) -> Vec<(String, String)> {
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    for piece in raw.split(',') {
        let name = piece.trim();
        if name.is_empty() || name.chars().count() > 64 {
            continue;
        }
        let slug = tag_slug(name);
        if slug.is_empty() || !seen.insert(slug.clone()) {
            continue;
        }
        out.push((name.to_string(), slug));
        if out.len() >= MAX_TAGS {
            break;
        }
    }
    out
}

/// Attach the tags in `raw` to a topic. Existing tags are reused; brand-new
/// tags are only minted when `user` meets the trust gate (others are silently
/// skipped). Does not remove tags already on the topic.
async fn apply_tags(
    state: &AppState,
    topic_id: Uuid,
    raw: &str,
    user: &users::Model,
) -> Result<(), StatusCode> {
    let may_create_tags = crate::trust::can_create_tags(user, state.config.min_trust_to_create_tag);
    let now = Utc::now();
    for (name, slug) in parse_tag_list(raw) {
        let tag = match tags::Entity::find()
            .filter(tags::Column::Slug.eq(&slug))
            .one(state.db.as_ref())
            .await
            .map_err(ise("look up tag"))?
        {
            Some(t) => Some(t),
            None if may_create_tags => tags::ActiveModel {
                id: Set(Uuid::now_v7()),
                name: Set(name),
                slug: Set(slug),
                created_at: Set(now.into()),
            }
            .insert(state.db.as_ref())
            .await
            .ok(),
            None => None, // not allowed to mint new tags
        };
        if let Some(tag) = tag {
            let already = topic_tags::Entity::find()
                .filter(topic_tags::Column::TopicId.eq(topic_id))
                .filter(topic_tags::Column::TagId.eq(tag.id))
                .one(state.db.as_ref())
                .await
                .map_err(ise("check topic tag"))?
                .is_some();
            if !already {
                topic_tags::ActiveModel {
                    id: Set(Uuid::now_v7()),
                    topic_id: Set(topic_id),
                    tag_id: Set(tag.id),
                }
                .insert(state.db.as_ref())
                .await
                .map_err(ise("insert topic tag"))?;
            }
        }
    }
    Ok(())
}

/// Build display rows for a set of loaded topics (category circle, author,
/// tags). Reused by category, tag, and search listings.
pub async fn build_topic_rows(
    state: &AppState,
    tree: &CategoryTree,
    loaded: Vec<(topics::Model, Option<users::Model>)>,
) -> Result<Vec<TopicRow>, StatusCode> {
    let topic_ids: Vec<Uuid> = loaded.iter().map(|(t, _)| t.id).collect();

    // Batch-load tags for all topics.
    let mut tag_map: std::collections::HashMap<Uuid, Vec<TagChip>> = std::collections::HashMap::new();
    if !topic_ids.is_empty() {
        let links = topic_tags::Entity::find()
            .filter(topic_tags::Column::TopicId.is_in(topic_ids.iter().copied()))
            .find_also_related(tags::Entity)
            .all(state.db.as_ref())
            .await
            .map_err(ise("load tags"))?;
        for (link, tag) in links {
            if let Some(t) = tag {
                tag_map
                    .entry(link.topic_id)
                    .or_default()
                    .push(TagChip { name: t.name, slug: t.slug });
            }
        }
    }

    Ok(loaded
        .into_iter()
        .map(|(t, u)| {
            let (cat_widget_bg, cat_name, cat_slug) = match tree.get(t.category_id) {
                Some(c) => (
                    color_widget_css(&tree.widget_colors(t.category_id)),
                    c.name.clone(),
                    c.slug.clone(),
                ),
                None => (color_widget_css(&[]), String::new(), String::new()),
            };
            TopicRow {
                tags: tag_map.remove(&t.id).unwrap_or_default(),
                id: t.id,
                title: t.title,
                is_pinned: t.is_pinned,
                is_closed: t.is_closed,
                posts_count: t.posts_count,
                views: t.views,
                bumped_at: rel(t.bumped_at),
                bumped_at_abs: abs(t.bumped_at),
                author: author_name(&u),
                author_id: t.user_id,
                author_has_avatar: u.as_ref().is_some_and(|u| u.avatar_content_type.is_some()),
                cat_widget_bg,
                cat_name,
                cat_slug,
            }
        })
        .collect())
}

/// Count non-deleted topics across a set of category ids.
async fn count_topics_in(state: &AppState, ids: &[Uuid]) -> Result<u64, StatusCode> {
    if ids.is_empty() {
        return Ok(0);
    }
    topics::Entity::find()
        .filter(topics::Column::CategoryId.is_in(ids.iter().copied()))
        .filter(topics::Column::DeletedAt.is_null())
        .count(state.db.as_ref())
        .await
        .map_err(ise("count topics"))
}

#[derive(Serialize)]
struct PostRow {
    id: Uuid,
    post_number: i32,
    cooked: String,
    created_at: String,
    created_at_abs: String,
    author: String,
    author_id: Uuid,
    author_has_avatar: bool,
    edited: bool,
    deleted: bool,
    deleted_by: Option<String>,
    can_edit: bool,
    can_restore: bool,
    bookmarked: bool,
    reactions: Vec<ReactionView>,
}

fn author_name(user: &Option<users::Model>) -> String {
    user.as_ref().map(|u| u.username.clone()).unwrap_or_else(|| "unknown".to_string())
}

async fn username_of(state: &AppState, id: Option<Uuid>) -> Option<String> {
    let id = id?;
    users::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .ok()
        .flatten()
        .map(|u| u.username)
}


/// Forum home — list categories with their topic counts.
pub async fn home(
    State(state): State<AppState>,
    user_context: Option<UserContext>,
) -> Result<Html<String>, StatusCode> {
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    let vis = tree.visible_category_ids(viewer_of(&user_context));
    let only_visible = |ids: Vec<Uuid>| -> Vec<Uuid> {
        ids.into_iter().filter(|i| vis.contains(i)).collect()
    };

    let mut rows = Vec::with_capacity(tree.roots().len());
    for &root in tree.roots() {
        if !vis.contains(&root) {
            continue;
        }
        let Some(c) = tree.get(root) else { continue };
        let topic_count =
            count_topics_in(&state, &only_visible(tree.self_and_descendants(root))).await?;

        let mut subcategories = Vec::new();
        for (id, depth) in tree.descendants_with_depth(root) {
            if !vis.contains(&id) {
                continue;
            }
            if let Some(sub) = tree.get(id) {
                subcategories.push(SubRow {
                    name: sub.name.clone(),
                    slug: sub.slug.clone(),
                    depth,
                    topic_count: count_topics_in(&state, &only_visible(tree.self_and_descendants(id)))
                        .await?,
                    widget_bg: color_widget_css(&tree.widget_colors(id)),
                });
            }
        }

        rows.push(CategoryRow {
            name: c.name.clone(),
            slug: c.slug.clone(),
            description: c.description.clone(),
            topic_count,
            widget_bg: color_widget_css(&tree.widget_colors(root)),
            subcategories,
        });
    }

    render(&state, "forum/home.html", context! {
        title => "Home",
        app_name => state.config.app_name,
        user => user_context.map(|c| c.user),
        categories => rows,
    })
}

#[derive(Debug, Deserialize)]
pub struct CategoryQuery {
    pub sort: Option<String>,
}

/// List the topics within a category.
pub async fn category_show(
    State(state): State<AppState>,
    Path(slug): Path<String>,
    Query(q): Query<CategoryQuery>,
    user_context: Option<UserContext>,
) -> Result<Html<String>, StatusCode> {
    let category = categories::Entity::find()
        .filter(categories::Column::Slug.eq(&slug))
        .one(state.db.as_ref())
        .await
        .map_err(ise("load category"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    let viewer = viewer_of(&user_context);
    if !tree.can_view(category.id, viewer) {
        return Err(StatusCode::NOT_FOUND);
    }
    let vis = tree.visible_category_ids(viewer);

    // Effective sort: explicit ?sort= wins, else the signed-in user's saved
    // preference, else latest. An explicit choice updates that preference.
    let requested = q.sort.as_deref().and_then(TopicSort::parse);
    let sort = requested
        .or_else(|| user_context.as_ref().and_then(|c| TopicSort::parse(&c.user.preferred_sort)))
        .unwrap_or(TopicSort::Latest);
    if let (Some(req), Some(ctx)) = (requested, user_context.as_ref()) {
        if ctx.user.preferred_sort != req.as_str() {
            let mut am: users::ActiveModel = ctx.user.clone().into();
            am.preferred_sort = Set(req.as_str().to_string());
            let _ = am.update(state.db.as_ref()).await;
        }
    }

    // Topics from this category AND every VISIBLE descendant roll up here.
    let include_ids: Vec<Uuid> = tree
        .self_and_descendants(category.id)
        .into_iter()
        .filter(|i| vis.contains(i))
        .collect();

    let mut loaded = topics::Entity::find()
        .filter(topics::Column::CategoryId.is_in(include_ids.iter().copied()))
        .filter(topics::Column::DeletedAt.is_null())
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load topics"))?;
    sort_topics(&mut loaded, sort);
    let rows = build_topic_rows(&state, &tree, loaded).await?;

    let ancestors: Vec<Crumb> = tree
        .ancestors(category.id)
        .into_iter()
        .filter_map(|id| tree.get(id).map(|c| Crumb { name: c.name.clone(), slug: c.slug.clone() }))
        .collect();

    let subcategories: Vec<ChipRow> = tree
        .children(category.id)
        .iter()
        .filter(|id| vis.contains(id))
        .filter_map(|&id| tree.get(id).map(|c| ChipRow {
            name: c.name.clone(),
            slug: c.slug.clone(),
            widget_bg: color_widget_css(&tree.widget_colors(id)),
        }))
        .collect();

    let category_widget_bg = color_widget_css(&tree.widget_colors(category.id));

    let watching = match user_context.as_ref() {
        Some(c) => category_watches::Entity::find()
            .filter(category_watches::Column::UserId.eq(c.user.id))
            .filter(category_watches::Column::CategoryId.eq(category.id))
            .one(state.db.as_ref())
            .await
            .map_err(ise("query watch"))?
            .is_some(),
        None => false,
    };

    render(&state, "forum/category.html", context! {
        title => category.name,
        app_name => state.config.app_name,
        user => user_context.map(|c| c.user),
        category => category,
        category_widget_bg => category_widget_bg,
        ancestors => ancestors,
        subcategories => subcategories,
        topics => rows,
        current_sort => sort.as_str(),
        slug => category.slug,
        watching => watching,
    })
}

#[derive(Serialize)]
struct ParticipantRow {
    id: Uuid,
    name: String,
    has_avatar: bool,
    count: i64,
}

/// Show a single topic with its posts.
pub async fn topic_show(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    headers: HeaderMap,
    user_context: Option<UserContext>,
) -> Result<Html<String>, StatusCode> {
    let topic = topics::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    let category = categories::Entity::find_by_id(topic.category_id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic category"))?;

    // Category read gating: hidden topics 404 for non-permitted viewers.
    {
        let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
        if !tree.can_view(topic.category_id, viewer_of(&user_context)) {
            return Err(StatusCode::NOT_FOUND);
        }
    }

    // (current user id, is_staff) for per-post + topic controls.
    let current = user_context.as_ref().map(|c| (c.user.id, c.user.is_staff));
    let is_staff = current.is_some_and(|(_, staff)| staff);
    let topic_deleted = topic.deleted_at.is_some();

    // A deleted topic still resolves (so links don't 404), but non-staff only
    // see a tombstone — never the content.
    if topic_deleted && !is_staff {
        return render(&state, "forum/topic_deleted.html", context! {
            title => "Topic removed",
            app_name => state.config.app_name,
            user => user_context.map(|c| c.user),
            category => category,
        });
    }

    let can_delete_topic =
        !topic_deleted && current.is_some_and(|(uid, staff)| staff || uid == topic.user_id);
    let can_restore_topic = topic_deleted && is_staff;

    // View counter — bump at most once per viewer per VIEW_WINDOW so constant
    // refreshing doesn't inflate the count. Keyed by user id when signed in,
    // else best-effort client IP.
    if !topic_deleted {
        let viewer = current
            .map(|(uid, _)| format!("u:{uid}"))
            .unwrap_or_else(|| format!("ip:{}", client_ip(&headers)));
        let should_bump = {
            let mut cache = state.view_throttle.lock().unwrap();
            let now = Instant::now();
            let key = (topic.id, viewer);
            let bump = cache
                .get(&key)
                .map(|&last| now.duration_since(last) >= VIEW_WINDOW)
                .unwrap_or(true);
            if bump {
                cache.insert(key, now);
                // Opportunistic prune so the map can't grow unbounded.
                if cache.len() > 50_000 {
                    cache.retain(|_, &mut last| now.duration_since(last) < VIEW_WINDOW);
                }
            }
            bump
        };
        if should_bump {
            let mut t: topics::ActiveModel = topic.clone().into();
            t.views = Set(topic.views + 1);
            let _ = t.update(state.db.as_ref()).await;
        }
    }

    let loaded = posts::Entity::find()
        .filter(posts::Column::TopicId.eq(topic.id))
        .order_by_asc(posts::Column::PostNumber)
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load posts"))?;

    // Which of these posts the current user has bookmarked.
    let bookmarked_ids: std::collections::HashSet<Uuid> = match current {
        Some((uid, _)) => bookmarks::Entity::find()
            .filter(bookmarks::Column::UserId.eq(uid))
            .filter(bookmarks::Column::PostId.is_in(loaded.iter().map(|(p, _)| p.id)))
            .all(state.db.as_ref())
            .await
            .map_err(ise("load bookmarks"))?
            .into_iter()
            .map(|b| b.post_id)
            .collect(),
        None => std::collections::HashSet::new(),
    };

    // Reaction bars for all posts in one shot.
    let rtypes = active_reaction_types(state.db.as_ref())
        .await
        .map_err(ise("load reaction types"))?;
    let post_ids: Vec<Uuid> = loaded.iter().map(|(p, _)| p.id).collect();
    let mut reaction_map =
        reaction_views_for_posts(state.db.as_ref(), &rtypes, &post_ids, current.map(|(uid, _)| uid))
            .await
            .map_err(ise("load reactions"))?;

    // Top other repliers in the thread (excludes the opening poster, most posts
    // first) — shown as a participants strip on wide screens.
    let participants: Vec<ParticipantRow> = {
        let mut pc: std::collections::HashMap<Uuid, (String, bool, i64)> =
            std::collections::HashMap::new();
        for (p, u) in &loaded {
            if p.deleted_at.is_some() || p.user_id == topic.user_id {
                continue;
            }
            let e = pc.entry(p.user_id).or_insert_with(|| {
                (
                    u.as_ref().map(|x| x.username.clone()).unwrap_or_else(|| "unknown".to_string()),
                    u.as_ref().is_some_and(|x| x.avatar_content_type.is_some()),
                    0,
                )
            });
            e.2 += 1;
        }
        let mut v: Vec<ParticipantRow> = pc
            .into_iter()
            .map(|(id, (name, has_avatar, count))| ParticipantRow { id, name, has_avatar, count })
            .collect();
        v.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(&b.name)));
        v.truncate(4);
        v
    };

    let mut rows = Vec::with_capacity(loaded.len());
    for (p, u) in loaded {
        let deleted = p.deleted_at.is_some();
        let can_edit = !deleted
            && current.is_some_and(|(uid, staff)| staff || uid == p.user_id);
        let can_restore = deleted && current.is_some_and(|(_, staff)| staff);
        let deleted_by = if deleted {
            username_of(&state, p.deleted_by_id).await
        } else {
            None
        };
        rows.push(PostRow {
            id: p.id,
            post_number: p.post_number,
            cooked: p.cooked,
            created_at: rel(p.created_at),
            created_at_abs: abs(p.created_at),
            author: author_name(&u),
            author_id: p.user_id,
            author_has_avatar: u.as_ref().is_some_and(|u| u.avatar_content_type.is_some()),
            edited: p.edit_count > 0,
            deleted,
            deleted_by,
            can_edit,
            can_restore,
            bookmarked: bookmarked_ids.contains(&p.id),
            reactions: reaction_map.remove(&p.id).unwrap_or_default(),
        });
    }

    let topic_tag_chips = tags_for_topic(&state, topic.id).await?;
    // Tag editing: topic author or staff, on a live topic.
    let can_edit_tags =
        !topic_deleted && current.is_some_and(|(uid, staff)| staff || uid == topic.user_id);
    let may_create_tags = user_context.as_ref().is_some_and(|c| {
        crate::trust::can_create_tags(&c.user, state.config.min_trust_to_create_tag)
    });

    render(&state, "forum/topic.html", context! {
        title => topic.title,
        app_name => state.config.app_name,
        user => user_context.map(|c| c.user),
        category => category,
        topic => topic,
        posts => rows,
        tags => topic_tag_chips,
        can_edit_tags => can_edit_tags,
        may_create_tags => may_create_tags,
        min_trust => state.config.min_trust_to_create_tag,
        participants => participants,
        topic_deleted => topic_deleted,
        can_delete_topic => can_delete_topic,
        can_restore_topic => can_restore_topic,
    })
}

#[derive(Debug, Deserialize)]
pub struct NewTopicForm {
    pub title: String,
    pub body: String,
    /// Comma-separated free-form tags (optional).
    pub tags: Option<String>,
}

/// Render the "new topic" form (auth required).
pub async fn new_topic_form(
    State(state): State<AppState>,
    Path(slug): Path<String>,
    user_context: UserContext,
) -> Result<Html<String>, StatusCode> {
    let category = categories::Entity::find()
        .filter(categories::Column::Slug.eq(&slug))
        .one(state.db.as_ref())
        .await
        .map_err(ise("load category"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    {
        let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
        if !tree.can_view(category.id, viewer_user(&user_context)) {
            return Err(StatusCode::NOT_FOUND);
        }
    }

    let may_create_tags =
        crate::trust::can_create_tags(&user_context.user, state.config.min_trust_to_create_tag);
    render(&state, "forum/new_topic.html", context! {
        title => "New topic",
        app_name => state.config.app_name,
        user => user_context.user,
        category => category,
        may_create_tags => may_create_tags,
        min_trust => state.config.min_trust_to_create_tag,
    })
}

/// Create a topic and its opening post (auth required).
pub async fn create_topic(
    State(state): State<AppState>,
    Path(slug): Path<String>,
    user_context: UserContext,
    Form(form): Form<NewTopicForm>,
) -> Result<Redirect, StatusCode> {
    let title = form.title.trim();
    let body = form.body.trim();
    if title.is_empty() || body.is_empty() {
        return Err(StatusCode::BAD_REQUEST);
    }

    let category = categories::Entity::find()
        .filter(categories::Column::Slug.eq(&slug))
        .one(state.db.as_ref())
        .await
        .map_err(ise("load category"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    if !tree.can_view(category.id, viewer_user(&user_context)) {
        return Err(StatusCode::NOT_FOUND);
    }

    let now = Utc::now();
    let topic_id = Uuid::now_v7();

    let topic = topics::ActiveModel {
        id: Set(topic_id),
        category_id: Set(category.id),
        user_id: Set(user_context.user.id),
        title: Set(title.to_string()),
        is_pinned: Set(false),
        is_closed: Set(false),
        views: Set(0),
        posts_count: Set(1),
        created_at: Set(now.into()),
        updated_at: Set(now.into()),
        bumped_at: Set(now.into()),
        deleted_at: Set(None),
        deleted_by_id: Set(None),
    };
    topic.insert(state.db.as_ref()).await.map_err(ise("insert topic"))?;

    let cooked = markdown::render(body);
    let post_id = Uuid::now_v7();
    let post = posts::ActiveModel {
        id: Set(post_id),
        topic_id: Set(topic_id),
        user_id: Set(user_context.user.id),
        post_number: Set(1),
        raw: Set(body.to_string()),
        cooked: Set(cooked.clone()),
        created_at: Set(now.into()),
        updated_at: Set(now.into()),
        edited_at: Set(None),
        edit_count: Set(0),
        last_editor_id: Set(None),
        deleted_at: Set(None),
        deleted_by_id: Set(None),
    };
    post.insert(state.db.as_ref()).await.map_err(ise("insert opening post"))?;
    record_revision(state.db.as_ref(), post_id, 1, user_context.user.id, body, &cooked, now.into())
        .await
        .map_err(ise("record opening revision"))?;

    // Free-form tags (created on demand; up to 5). Minting NEW tags requires a
    // trust level; lower-tier users may still apply existing tags.
    if let Some(raw) = form.tags.as_deref() {
        apply_tags(&state, topic_id, raw, &user_context.user).await?;
    }

    // Notify watchers of this category and its ancestors (best-effort).
    let mut watch_ids = tree.ancestors(category.id);
    watch_ids.push(category.id);
    if let Err(e) = crate::handlers::notifications::notify_new_topic(
        state.db.as_ref(),
        topic_id,
        user_context.user.id,
        &watch_ids,
    )
    .await
    {
        error!(error = %e, "notify watchers failed");
    }

    if let Err(e) = crate::trust::recompute(state.db.as_ref(), &user_context.user).await {
        error!(error = %e, "trust recompute failed");
    }

    Ok(Redirect::to(&format!("/t/{topic_id}")))
}

#[derive(Debug, Deserialize)]
pub struct ReplyForm {
    pub body: String,
}

/// Add a reply to a topic (auth required). Returns the rendered post fragment
/// for htmx, or redirects back to the topic for a plain form submit.
pub async fn create_post(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    HxRequest(is_htmx): HxRequest,
    user_context: UserContext,
    Form(form): Form<ReplyForm>,
) -> Result<axum::response::Response, StatusCode> {
    let body = form.body.trim();
    if body.is_empty() {
        return Err(StatusCode::BAD_REQUEST);
    }

    let topic = topics::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic for reply"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    {
        let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
        if !tree.can_view(topic.category_id, viewer_user(&user_context)) {
            return Err(StatusCode::NOT_FOUND);
        }
    }

    if topic.is_closed {
        return Err(StatusCode::FORBIDDEN);
    }

    let next_number = topic.posts_count + 1;
    let now = Utc::now();
    let cooked = markdown::render(body);

    let post = posts::ActiveModel {
        id: Set(Uuid::now_v7()),
        topic_id: Set(topic.id),
        user_id: Set(user_context.user.id),
        post_number: Set(next_number),
        raw: Set(body.to_string()),
        cooked: Set(cooked.clone()),
        created_at: Set(now.into()),
        updated_at: Set(now.into()),
        edited_at: Set(None),
        edit_count: Set(0),
        last_editor_id: Set(None),
        deleted_at: Set(None),
        deleted_by_id: Set(None),
    };
    let post = post.insert(state.db.as_ref()).await.map_err(ise("insert reply"))?;
    record_revision(state.db.as_ref(), post.id, 1, user_context.user.id, body, &cooked, now.into())
        .await
        .map_err(ise("record reply revision"))?;

    let mut t: topics::ActiveModel = topic.clone().into();
    t.posts_count = Set(next_number);
    t.bumped_at = Set(now.into());
    t.update(state.db.as_ref()).await.map_err(ise("bump topic"))?;

    if let Err(e) = crate::trust::recompute(state.db.as_ref(), &user_context.user).await {
        error!(error = %e, "trust recompute failed");
    }

    if is_htmx {
        let row = PostRow {
            id: post.id,
            post_number: post.post_number,
            cooked,
            created_at: rel(post.created_at),
            created_at_abs: abs(post.created_at),
            author: user_context.user.username.clone(),
            author_id: user_context.user.id,
            author_has_avatar: user_context.user.avatar_content_type.is_some(),
            edited: false,
            deleted: false,
            deleted_by: None,
            can_edit: true,
            can_restore: false,
            bookmarked: false,
            reactions: active_reaction_types(state.db.as_ref())
                .await
                .map_err(ise("load reaction types"))?
                .into_iter()
                .map(|t| ReactionView { key: t.key, emoji: t.emoji, count: 0, reacted: false })
                .collect(),
        };
        let html = render(&state, "forum/_post.html", context! {
            post => row,
            user => user_context.user.clone(),
        })?;
        Ok(html.into_response())
    } else {
        Ok(Redirect::to(&format!("/t/{}", topic.id)).into_response())
    }
}

#[derive(Debug, Deserialize)]
pub struct TopicTagsForm {
    /// Comma-separated tag names; replaces the topic's current tags.
    #[serde(default)]
    pub tags: String,
}

/// Replace a topic's tags (topic author or staff). Same rules as at creation:
/// up to 5, slug-deduplicated, and minting brand-new tags needs the trust gate
/// (existing tags can always be applied). htmx gets the re-rendered tag bar;
/// plain form posts redirect back to the topic.
pub async fn update_topic_tags(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    HxRequest(is_htmx): HxRequest,
    user_context: UserContext,
    Form(form): Form<TopicTagsForm>,
) -> Result<axum::response::Response, StatusCode> {
    let topic = topics::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic for tag edit"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    {
        let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
        if !tree.can_view(topic.category_id, viewer_user(&user_context)) {
            return Err(StatusCode::NOT_FOUND);
        }
    }
    if topic.deleted_at.is_some() {
        return Err(StatusCode::NOT_FOUND);
    }
    if !(user_context.user.is_staff || user_context.user.id == topic.user_id) {
        return Err(StatusCode::FORBIDDEN);
    }

    // Replace: drop the current links, then apply the submitted list. Tag rows
    // themselves are kept (other topics may use them; /tags lists zero counts).
    topic_tags::Entity::delete_many()
        .filter(topic_tags::Column::TopicId.eq(topic.id))
        .exec(state.db.as_ref())
        .await
        .map_err(ise("clear topic tags"))?;
    apply_tags(&state, topic.id, &form.tags, &user_context.user).await?;

    let mut t: topics::ActiveModel = topic.clone().into();
    t.updated_at = Set(Utc::now().into());
    t.update(state.db.as_ref()).await.map_err(ise("touch topic"))?;

    if is_htmx {
        let tag_chips = tags_for_topic(&state, topic.id).await?;
        let may_create_tags =
            crate::trust::can_create_tags(&user_context.user, state.config.min_trust_to_create_tag);
        let html = render(&state, "forum/_topic_tags.html", context! {
            topic => topic,
            tags => tag_chips,
            can_edit_tags => true,
            may_create_tags => may_create_tags,
            min_trust => state.config.min_trust_to_create_tag,
        })?;
        Ok(html.into_response())
    } else {
        Ok(Redirect::to(&format!("/t/{}", topic.id)).into_response())
    }
}

/// Soft-delete a topic (author or staff). The row stays so `/t/{id}` keeps
/// resolving; it just drops out of listings and shows a tombstone.
pub async fn delete_topic(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user_context: UserContext,
) -> Result<Redirect, StatusCode> {
    let topic = topics::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic for delete"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    if !(user_context.user.is_staff || user_context.user.id == topic.user_id) {
        return Err(StatusCode::FORBIDDEN);
    }

    let category_id = topic.category_id;
    if topic.deleted_at.is_none() {
        let now = Utc::now();
        let mut t: topics::ActiveModel = topic.into();
        t.deleted_at = Set(Some(now.into()));
        t.deleted_by_id = Set(Some(user_context.user.id));
        t.updated_at = Set(now.into());
        t.update(state.db.as_ref()).await.map_err(ise("delete topic"))?;
    }

    // Send them back to the category listing.
    let slug = categories::Entity::find_by_id(category_id)
        .one(state.db.as_ref())
        .await
        .ok()
        .flatten()
        .map(|c| c.slug)
        .unwrap_or_default();
    Ok(Redirect::to(&format!("/c/{slug}")))
}

/// Restore a soft-deleted topic — staff only.
pub async fn restore_topic(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    user_context: UserContext,
) -> Result<Redirect, StatusCode> {
    if !user_context.user.is_staff {
        return Err(StatusCode::FORBIDDEN);
    }
    let topic = topics::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load topic for restore"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    if topic.deleted_at.is_some() {
        let mut t: topics::ActiveModel = topic.into();
        t.deleted_at = Set(None);
        t.deleted_by_id = Set(None);
        t.updated_at = Set(Utc::now().into());
        t.update(state.db.as_ref()).await.map_err(ise("restore topic"))?;
    }
    Ok(Redirect::to(&format!("/t/{id}")))
}

/// Render a template, mapping load/render errors to 500.
fn render(
    state: &AppState,
    name: &str,
    ctx: minijinja::Value,
) -> Result<Html<String>, StatusCode> {
    let template = state
        .env
        .get_template(name)
        .map_err(|e| {
            error!(error = %e, template = name, "load template failed");
            StatusCode::INTERNAL_SERVER_ERROR
        })?;
    let rendered = template.render(ctx).map_err(|e| {
        error!(error = %e, template = name, "render template failed");
        StatusCode::INTERNAL_SERVER_ERROR
    })?;
    Ok(Html(rendered))
}