use super::response::success_askama;
use super::route_prelude::*;
use std::collections::{HashMap, HashSet};

#[derive(Template, Clone)]
#[template(path = "followers.gmi", escape = "txt")]
struct FollowersTemplate {
    followers: HashSet<PublicKey>,
    metadata_events: HashMap<PublicKey, Event>,
}

pub async fn person_followers_list(
    ctx: RouteContext,
    user: &'static mut CaracalUser,
) -> Result<Response, UserError> {
    let npub = ctx.parameters.get("npub").ok_or(UserError::InvalidParams)?;
    let pubkey = PublicKey::parse(npub)?;

    let events = user
        .client
        .fetch_combined_events(
            Filter::new().kind(Kind::ContactList).pubkey(pubkey),
            dur_parse("10s").unwrap(),
        )
        .await?;

    let followers = events.iter().map(|ev| ev.pubkey).collect::<HashSet<_>>();
    let metadata_events = user
        .db_metadata_events_for(followers.clone().into_iter())
        .await;

    Ok(success_askama!(FollowersTemplate {
        followers,
        metadata_events
    }))
}
