use super::route_prelude::*;
use crate::{
    nostru,
    rendering::{NoteRenderOptions, render_notes},
};

#[derive(Template, Clone)]
#[template(path = "outbox.gmi", escape = "txt")]
struct OutboxTemplate {
    note_blocks: Vec<Block>,
}

pub async fn outbox(
    _ctx: RouteContext,
    user: &'static mut CaracalUser,
) -> Response {
    let Ok(pubkey) = user.signer.get_public_key().await else {
        return Response::temporary_failure(t!("signer_error"));
    };

    let Ok(events) = user
        .client
        .fetch_combined_events(
            nostru::notes_filter().author(pubkey),
            std::time::Duration::from_secs(5),
        )
        .await
    else {
        return Response::temporary_failure(t!("fetch_events_failed"));
    };

    if let Ok(note_blocks) = render_notes(
        events,
        &user.client,
        None,
        None,
        NoteRenderOptions::default() | NoteRenderOptions::DELETE,
    )
    .await
    {
        Response::success(WindTemplate::render(OutboxTemplate { note_blocks }))
    } else {
        Response::temporary_failure("Failed to render notes")
    }
}
