use nostr_sdk::prelude::*;
use windmark_titanesque::{context::RouteContext, response::Response};

use crate::aska::WindTemplate;
use crate::routes::gem;
use crate::user::CaracalUser;
use crate::{nostru, rendering};
use askama::Template;
use mdiu::Block;
use rust_i18n::t;

#[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
        .database()
        .query(nostru::notes_filter().author(pubkey))
        .await
    else {
        return Response::temporary_failure(t!("fetch_events_failed"));
    };

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