use super::route_prelude::*;
use crate::nostru;
use crate::rendering::lnk;
use crate::rendering::note_thread_uri;
use crate::util::extract_first_words;

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

pub async fn inbox(
    _ctx: RouteContext,
    user: &'static mut CaracalUser,
) -> Result<Response, UserError> {
    let mut blocks = vec![];

    let pubkey = user.public_key().await?;

    let mentions_filter = Filter::new().kind(Kind::TextNote).pubkey(pubkey);

    let mut events = user
        .client
        .fetch_combined_events(mentions_filter, Duration::from_secs(5))
        .await?;

    // Get reactions to notes we wrote
    for event in user
        .db_query(Filter::new().kind(Kind::TextNote).author(pubkey))
        .await?
    {
        events.extend(
            user.db_query(Filter::new().kind(Kind::Reaction).event(event.id))
                .await?,
        );
    }

    for event in events {
        match event.kind {
            Kind::TextNote | Kind::LongFormTextNote => {
                if let Ok(mut blks) = render_note(
                    &user.client,
                    &event,
                    nostru::get_user_metadata(&user.client, event.pubkey).await,
                    NoteRenderOptions::default(),
                )
                .await
                {
                    blocks.append(&mut blks);
                }
            }
            Kind::Reaction => {
                let Some(event_id) = event.tags.event_ids().next() else {
                    continue;
                };

                let Ok(note_event) =
                    user.db_query_first(Filter::new().id(*event_id)).await
                else {
                    continue;
                };

                let emoji = nostru::reaction_emoji(&event);

                blocks.push(Block::Text(Content::new(format!(
                    "# {} {}",
                    emoji,
                    t!(
                        "reacted_to_your_post",
                        user = pubkey_label(&event.pubkey, &user.client).await,
                        reaction = emoji
                    )
                ))?));

                blocks.push(lnk(
                    note_thread_uri(event_id)?,
                    extract_first_words(&note_event, 16),
                ));
            }
            _ => (),
        }
    }

    Ok(Response::success(WindTemplate::render(InboxTemplate {
        blocks,
    })))
}
