use std::collections::HashMap;

use nostr_sdk::prelude::*;

use super::core::CaracalUser;
use crate::relays::default_relays;

impl CaracalUser {
    pub async fn advertise_relay_list(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let relay_config = self.relay_list_config();

        let mut relay_metadata: HashMap<RelayUrl, Option<RelayMetadata>> =
            HashMap::new();

        for rurl in relay_config.read_relays {
            let _ = self.client.add_read_relay(&rurl).await;

            relay_metadata.insert(rurl, Some(RelayMetadata::Read));
        }

        for wurl in relay_config.write_relays {
            let _ = self.client.add_write_relay(&wurl).await;

            relay_metadata.insert(wurl, Some(RelayMetadata::Write));
        }

        let relay_list_builder = EventBuilder::relay_list(relay_metadata);

        self.client
            .send_event_builder_to(default_relays(), relay_list_builder)
            .await?;

        /* Send (fixed list for now to make the DMs UI work) inbox relays event */
        let inboxr: Vec<&str> =
            vec!["wss://relay.damus.io", "wss://nostr.bitcoiner.social"];

        let inbox_relays_builder = EventBuilder::new(Kind::InboxRelays, "")
            .tags(
                inboxr
                    .into_iter()
                    .map(|ir| Tag::custom(TagKind::Relay, vec![ir])),
            );

        self.client
            .send_event_builder_to(default_relays(), inbox_relays_builder)
            .await?;

        Ok(())
    }
}
