/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use std::{borrow::Cow, sync::Arc};

use crate::{
    delivery::AutogeneratedMessage,
    ingest::{EmailIngest, IngestEmail, IngestSource, IngestedEmail},
    mailbox::{MailboxFnc, INBOX_ID, TRASH_ID},
};
use common::{auth::AccessToken, scripts::plugins::PluginContext, Server};
use directory::{backend::internal::PrincipalField, Permission, QueryBy};
use jmap_proto::{
    object::Object,
    types::{collection::Collection, id::Id, keyword::Keyword, property::Property, value::Value},
};
use mail_parser::MessageParser;
use serde::ser::SerializeSeq;
use sieve::{Envelope, Event, Input, Mailbox, Recipient, Sieve};
use store::{
    ahash::AHashSet,
    blake3,
    query::Filter,
    write::{assert::HashedValue, now, BatchBuilder, Bincode, BlobOp, F_VALUE},
    Deserialize, Serialize,
};
use trc::{AddContext, SieveEvent};

use std::future::Future;

struct SieveMessage<'x> {
    pub raw_message: Cow<'x, [u8]>,
    pub file_into: Vec<u32>,
    pub flags: Vec<Keyword>,
}

pub struct ActiveScript {
    pub document_id: u32,
    pub script_name: String,
    pub script: Arc<Sieve>,
    pub seen_ids: SeenIds,
}

#[derive(Debug, Clone)]
pub struct SeenIdHash {
    hash: [u8; 32],
    expiry: u64,
}

#[derive(Debug, Clone, Default)]
pub struct SeenIds {
    pub ids: AHashSet<SeenIdHash>,
    pub has_changes: bool,
}

pub trait SieveScriptIngest: Sync + Send {
    #[allow(clippy::too_many_arguments)]
    fn sieve_script_ingest(
        &self,
        access_token: &AccessToken,
        raw_message: &[u8],
        envelope_from: &str,
        envelope_to: &str,
        session_id: u64,
        active_script: ActiveScript,
        autogenerated: &mut Vec<AutogeneratedMessage>,
    ) -> impl Future<Output = trc::Result<IngestedEmail>> + Send;

    fn sieve_script_get_active(
        &self,
        account_id: u32,
    ) -> impl Future<Output = trc::Result<Option<ActiveScript>>> + Send;

    fn sieve_script_get_by_name(
        &self,
        account_id: u32,
        name: &str,
    ) -> impl Future<Output = trc::Result<Option<Sieve>>> + Send;

    fn sieve_script_compile(
        &self,
        account_id: u32,
        document_id: u32,
    ) -> impl Future<Output = trc::Result<(Sieve, Object<Value>)>> + Send;
}

impl SieveScriptIngest for Server {
    #[allow(clippy::blocks_in_conditions)]
    async fn sieve_script_ingest(
        &self,
        access_token: &AccessToken,
        raw_message: &[u8],
        envelope_from: &str,
        envelope_to: &str,
        session_id: u64,
        mut active_script: ActiveScript,
        autogenerated: &mut Vec<AutogeneratedMessage>,
    ) -> trc::Result<IngestedEmail> {
        // Parse message
        let message = if let Some(message) = MessageParser::new().parse(raw_message) {
            message
        } else {
            return Err(
                trc::EventType::MessageIngest(trc::MessageIngestEvent::Error)
                    .ctx(trc::Key::Code, 550)
                    .ctx(trc::Key::Reason, "Failed to parse e-mail message."),
            );
        };

        // Obtain mailboxIds
        let account_id = access_token.primary_id;
        let mailbox_ids = self
            .mailbox_get_or_create(account_id)
            .await
            .caused_by(trc::location!())?;

        // Create Sieve instance
        let mut instance = self.core.sieve.untrusted_runtime.filter_parsed(message);

        // Set account name and email
        let mail_from = self
            .core
            .storage
            .directory
            .query(QueryBy::Id(account_id), false)
            .await
            .caused_by(trc::location!())?
            .and_then(|mut p| {
                instance.set_user_full_name(p.description().unwrap_or_else(|| p.name()));
                p.take_str_array(PrincipalField::Emails)
                    .unwrap_or_default()
                    .into_iter()
                    .next()
            });

        // Set account address
        let mail_from = mail_from.unwrap_or_else(|| envelope_to.to_string());
        instance.set_user_address(&mail_from);

        // Set envelope
        instance.set_envelope(Envelope::From, envelope_from);
        instance.set_envelope(Envelope::To, envelope_to);

        let mut input = Input::script(active_script.script_name, active_script.script.clone());

        let mut do_discard = false;
        let mut do_deliver = false;

        let mut new_ids = AHashSet::new();
        let mut reject_reason = None;
        let mut messages: Vec<SieveMessage> = vec![SieveMessage {
            raw_message: raw_message.into(),
            file_into: Vec::new(),
            flags: Vec::new(),
        }];
        let now = now();
        let mut ingested_message = IngestedEmail {
            id: Id::default(),
            change_id: u64::MAX,
            blob_id: Default::default(),
            size: raw_message.len(),
            imap_uids: Vec::new(),
        };

        while let Some(event) = instance.run(input) {
            match event {
                Ok(event) => match event {
                    Event::IncludeScript { name, .. } => match &name {
                        sieve::Script::Personal(name_) => {
                            if let Ok(Some(script)) =
                                self.sieve_script_get_by_name(account_id, name_).await
                            {
                                input = Input::script(name, script);
                            } else {
                                input = false.into();
                            }
                        }
                        sieve::Script::Global(name_) => {
                            if let Some(script) =
                                self.get_untrusted_sieve_script(&name_.to_lowercase(), session_id)
                            {
                                input = Input::script(name, script.clone());
                            } else {
                                input = false.into();
                            }
                        }
                    },
                    Event::MailboxExists {
                        mailboxes,
                        special_use,
                    } => {
                        if !mailboxes.is_empty() {
                            let mut special_use_ids = Vec::with_capacity(special_use.len());
                            for role in special_use {
                                special_use_ids.push(if role.eq_ignore_ascii_case("inbox") {
                                    INBOX_ID
                                } else if role.eq_ignore_ascii_case("trash") {
                                    TRASH_ID
                                } else {
                                    let mut mailbox_id = u32::MAX;
                                    let role = role.to_ascii_lowercase();
                                    if is_valid_role(&role) {
                                        if let Ok(Some(mailbox_id_)) =
                                            self.mailbox_get_by_role(account_id, &role).await
                                        {
                                            mailbox_id = mailbox_id_;
                                        }
                                    }
                                    mailbox_id
                                });
                            }

                            let mut result = true;
                            for mailbox in mailboxes {
                                match mailbox {
                                    Mailbox::Name(name) => {
                                        if !matches!(
                                            self.mailbox_get_by_name(account_id, &name).await,
                                            Ok(Some(document_id)) if special_use_ids.is_empty() ||
                                            special_use_ids.contains(&document_id)
                                        ) {
                                            result = false;
                                            break;
                                        }
                                    }
                                    Mailbox::Id(id) => {
                                        if !matches!(Id::from_bytes(id.as_bytes()), Some(id) if
                                                            mailbox_ids.contains(id.document_id()) &&
                                                            (special_use_ids.is_empty() ||
                                                            special_use_ids.contains(&id.document_id())))
                                        {
                                            result = false;
                                            break;
                                        }
                                    }
                                }
                            }
                            input = result.into();
                        } else if !special_use.is_empty() {
                            let mut result = true;

                            for role in special_use {
                                if !role.eq_ignore_ascii_case("inbox")
                                    && !role.eq_ignore_ascii_case("trash")
                                {
                                    let role = role.to_ascii_lowercase();
                                    if !is_valid_role(&role)
                                        || !matches!(
                                            self.mailbox_get_by_role(account_id, &role).await,
                                            Ok(Some(_))
                                        )
                                    {
                                        result = false;
                                        break;
                                    }
                                }
                            }
                            input = result.into();
                        } else {
                            input = false.into();
                        }
                    }
                    Event::DuplicateId { id, expiry, last } => {
                        let id_hash = SeenIdHash::new(&id, expiry + now);
                        let seen_id = active_script.seen_ids.ids.contains(&id_hash);
                        if !seen_id || last {
                            new_ids.insert(id_hash);
                        }

                        input = seen_id.into();
                    }
                    Event::Discard => {
                        do_discard = true;
                        input = true.into();
                    }
                    Event::Reject { reason, .. } => {
                        reject_reason = reason.into();
                        do_discard = true;
                        input = true.into();
                    }
                    Event::Keep { flags, message_id } => {
                        if let Some(message) = messages.get_mut(message_id) {
                            message.flags = flags.into_iter().map(Keyword::from).collect();
                            if !message.file_into.contains(&INBOX_ID) {
                                message.file_into.push(INBOX_ID);
                            }
                            do_deliver = true;
                        } else {
                            trc::event!(
                                Sieve(SieveEvent::UnexpectedError),
                                Details = "Unknown message id.",
                                MessageId = message_id,
                                SpanId = session_id
                            );
                        }
                        input = true.into();
                    }
                    Event::FileInto {
                        folder,
                        flags,
                        mailbox_id,
                        special_use,
                        create,
                        message_id,
                    } => {
                        let mut target_id = u32::MAX;

                        // Find mailbox by Id
                        if let Some(mailbox_id) =
                            mailbox_id.and_then(|m| Id::from_bytes(m.as_bytes()))
                        {
                            let mailbox_id = mailbox_id.document_id();
                            if mailbox_ids.contains(mailbox_id) {
                                target_id = mailbox_id;
                            }
                        }

                        // Find mailbox by role
                        if let Some(special_use) = special_use {
                            if target_id == u32::MAX {
                                if special_use.eq_ignore_ascii_case("inbox") {
                                    target_id = INBOX_ID;
                                } else if special_use.eq_ignore_ascii_case("trash") {
                                    target_id = TRASH_ID;
                                } else {
                                    let role = special_use.to_ascii_lowercase();
                                    if is_valid_role(&role) {
                                        if let Ok(Some(mailbox_id_)) =
                                            self.mailbox_get_by_role(account_id, &role).await
                                        {
                                            target_id = mailbox_id_;
                                        }
                                    }
                                }
                            }
                        }

                        // Find mailbox by name
                        if target_id == u32::MAX {
                            if !create {
                                if let Ok(Some(document_id)) =
                                    self.mailbox_get_by_name(account_id, &folder).await
                                {
                                    target_id = document_id;
                                }
                            } else if let Ok(Some((document_id, changes))) =
                                self.mailbox_create_path(account_id, &folder).await
                            {
                                target_id = document_id;
                                if let Some(change_id) = changes {
                                    ingested_message.change_id = change_id;
                                }
                            }
                        }

                        // Default to Inbox
                        if target_id == u32::MAX {
                            target_id = INBOX_ID;
                        }

                        if let Some(message) = messages.get_mut(message_id) {
                            message.flags = flags.into_iter().map(Keyword::from).collect();
                            if !message.file_into.contains(&target_id) {
                                message.file_into.push(target_id);
                            }
                            do_deliver = true;
                        } else {
                            trc::event!(
                                Sieve(SieveEvent::UnexpectedError),
                                Details = "Unknown message id.",
                                MessageId = message_id,
                                SpanId = session_id
                            );
                        }
                        input = true.into();
                    }
                    Event::SendMessage {
                        recipient,
                        message_id,
                        ..
                    } => {
                        input = true.into();
                        if let Some(message) = messages.get(message_id) {
                            let recipients = match recipient {
                                Recipient::Address(rcpt) => vec![rcpt],
                                Recipient::Group(rcpts) => rcpts,
                                Recipient::List(_) => {
                                    // Not yet implemented
                                    continue;
                                }
                            };

                            if message.raw_message.len() <= self.core.jmap.mail_max_size {
                                trc::event!(
                                    Sieve(SieveEvent::SendMessage),
                                    From = mail_from.clone(),
                                    To = recipients
                                        .iter()
                                        .map(|r| trc::Value::String(r.clone()))
                                        .collect::<Vec<_>>(),
                                    Size = message.raw_message.len(),
                                    SpanId = session_id
                                );

                                autogenerated.push(AutogeneratedMessage {
                                    sender_address: mail_from.clone(),
                                    recipients,
                                    message: message.raw_message.to_vec(),
                                });
                            } else {
                                trc::event!(
                                    Sieve(SieveEvent::MessageTooLarge),
                                    From = mail_from.clone(),
                                    To = recipients
                                        .iter()
                                        .map(|r| trc::Value::String(r.clone()))
                                        .collect::<Vec<_>>(),
                                    Size = message.raw_message.len(),
                                    Limit = self.core.jmap.mail_max_size,
                                    SpanId = session_id,
                                );
                            }
                        } else {
                            trc::event!(
                                Sieve(SieveEvent::UnexpectedError),
                                Details = "Unknown message id.",
                                MessageId = message_id,
                                SpanId = session_id
                            );

                            continue;
                        }
                    }
                    Event::ListContains { .. }
                    | Event::Notify { .. }
                    | Event::SetEnvelope { .. } => {
                        // Not allowed
                        input = false.into();
                    }
                    Event::Function { id, arguments } => {
                        input = self
                            .core
                            .run_plugin(
                                id,
                                PluginContext {
                                    session_id,
                                    server: self,
                                    message: instance.message(),
                                    modifications: &mut Vec::new(),
                                    access_token: access_token.into(),
                                    arguments,
                                },
                            )
                            .await;
                    }
                    Event::CreatedMessage { message, .. } => {
                        messages.push(SieveMessage {
                            raw_message: message.into(),
                            file_into: Vec::new(),
                            flags: Vec::new(),
                        });
                        input = true.into();
                    }
                },

                #[cfg(feature = "test_mode")]
                Err(sieve::runtime::RuntimeError::ScriptErrorMessage(err)) => {
                    panic!("Sieve test failed: {}", err);
                }

                Err(err) => {
                    trc::event!(
                        Sieve(SieveEvent::RuntimeError),
                        Reason = err.to_string(),
                        SpanId = session_id
                    );

                    input = true.into();
                }
            }
        }

        // Fail-safe, no discard and no keep seen, assume that something went wrong and file anyway.
        if !do_deliver && !do_discard {
            messages[0].file_into.push(INBOX_ID);
        }

        // Deliver messages
        let mut last_temp_error = None;
        let mut has_delivered = false;
        let can_spam_train = self.email_bayes_can_train(access_token);
        for (message_id, sieve_message) in messages.into_iter().enumerate() {
            if !sieve_message.file_into.is_empty() {
                // Parse message if needed
                let message = if message_id == 0 && !instance.has_message_changed() {
                    instance.take_message()
                } else if let Some(message) =
                    MessageParser::new().parse(sieve_message.raw_message.as_ref())
                {
                    message
                } else {
                    trc::event!(
                        Sieve(SieveEvent::UnexpectedError),
                        Details = "Failed to parse Sieve generated message.",
                        SpanId = session_id
                    );

                    continue;
                };

                // Deliver message
                match self
                    .email_ingest(IngestEmail {
                        raw_message: &sieve_message.raw_message,
                        message: message.into(),
                        resource: access_token.as_resource_token(),
                        mailbox_ids: sieve_message.file_into,
                        keywords: sieve_message.flags,
                        received_at: None,
                        source: IngestSource::Smtp {
                            deliver_to: envelope_to,
                        },
                        spam_classify: access_token.has_permission(Permission::SpamFilterClassify),
                        spam_train: can_spam_train,
                        session_id,
                    })
                    .await
                {
                    Ok(ingested_message_) => {
                        has_delivered = true;
                        ingested_message = ingested_message_;
                    }
                    Err(err) => {
                        last_temp_error = err.into();
                    }
                }
            }
        }

        // Save new ids script changes
        if !new_ids.is_empty() || active_script.seen_ids.has_changes {
            active_script.seen_ids.ids.extend(new_ids);
            let mut batch = BatchBuilder::new();
            batch
                .with_account_id(account_id)
                .with_collection(Collection::SieveScript)
                .update_document(active_script.document_id)
                .value(
                    Property::EmailIds,
                    Bincode::new(active_script.seen_ids),
                    F_VALUE,
                );
            if let Err(err) = self.store().write(batch).await.caused_by(trc::location!()) {
                trc::error!(err.details("Failed to save Sieve seen ids changes."));
            }
        }

        if let Some(reject_reason) = reject_reason {
            Err(
                trc::EventType::MessageIngest(trc::MessageIngestEvent::Error)
                    .ctx(trc::Key::Code, 571)
                    .ctx(trc::Key::Reason, reject_reason),
            )
        } else if has_delivered || last_temp_error.is_none() {
            Ok(ingested_message)
        } else {
            // There were problems during delivery
            #[allow(clippy::unnecessary_unwrap)]
            Err(last_temp_error.unwrap())
        }
    }

    async fn sieve_script_get_active(&self, account_id: u32) -> trc::Result<Option<ActiveScript>> {
        // Find the currently active script
        if let Some(document_id) = self
            .store()
            .filter(
                account_id,
                Collection::SieveScript,
                vec![Filter::eq(Property::IsActive, 1u32)],
            )
            .await
            .caused_by(trc::location!())?
            .results
            .min()
        {
            let (script, mut script_object) =
                self.sieve_script_compile(account_id, document_id).await?;
            Ok(Some(ActiveScript {
                document_id,
                script: Arc::new(script),
                script_name: script_object
                    .properties
                    .remove(&Property::Name)
                    .and_then(|name| name.try_unwrap_string())
                    .unwrap_or_else(|| account_id.to_string()),
                seen_ids: self
                    .get_property::<Bincode<SeenIds>>(
                        account_id,
                        Collection::SieveScript,
                        document_id,
                        Property::EmailIds,
                    )
                    .await?
                    .map(|seen_ids| seen_ids.inner)
                    .unwrap_or_default(),
            }))
        } else {
            Ok(None)
        }
    }

    async fn sieve_script_get_by_name(
        &self,
        account_id: u32,
        name: &str,
    ) -> trc::Result<Option<Sieve>> {
        // Find the script by name
        if let Some(document_id) = self
            .store()
            .filter(
                account_id,
                Collection::SieveScript,
                vec![Filter::eq(Property::Name, name)],
            )
            .await
            .caused_by(trc::location!())?
            .results
            .min()
        {
            self.sieve_script_compile(account_id, document_id)
                .await
                .map(|(sieve, _)| Some(sieve))
        } else {
            Ok(None)
        }
    }

    #[allow(clippy::blocks_in_conditions)]
    async fn sieve_script_compile(
        &self,
        account_id: u32,
        document_id: u32,
    ) -> trc::Result<(Sieve, Object<Value>)> {
        // Obtain script object
        let script_object = self
            .get_property::<HashedValue<Object<Value>>>(
                account_id,
                Collection::SieveScript,
                document_id,
                Property::Value,
            )
            .await?
            .ok_or_else(|| {
                trc::StoreEvent::NotFound
                    .into_err()
                    .caused_by(trc::location!())
                    .document_id(document_id)
            })?;

        // Obtain the sieve script length
        let (script_offset, blob_id) = script_object
            .inner
            .properties
            .get(&Property::BlobId)
            .and_then(|v| v.as_blob_id())
            .and_then(|v| (v.section.as_ref()?.size, v).into())
            .ok_or_else(|| {
                trc::StoreEvent::NotFound
                    .into_err()
                    .caused_by(trc::location!())
                    .document_id(document_id)
            })?;

        // Obtain the sieve script blob
        let script_bytes = self
            .core
            .storage
            .blob
            .get_blob(blob_id.hash.as_ref(), 0..usize::MAX)
            .await
            .caused_by(trc::location!())?
            .ok_or_else(|| {
                trc::StoreEvent::NotFound
                    .into_err()
                    .caused_by(trc::location!())
                    .document_id(document_id)
            })?;

        // Obtain the precompiled script
        if let Some(sieve) = script_bytes
            .get(script_offset..)
            .and_then(|bytes| Bincode::<Sieve>::deserialize(bytes).ok())
        {
            Ok((sieve.inner, script_object.inner))
        } else {
            // Deserialization failed, probably because the script compiler version changed
            match self.core.sieve.untrusted_compiler.compile(
                script_bytes.get(0..script_offset).ok_or_else(|| {
                    trc::StoreEvent::NotFound
                        .into_err()
                        .caused_by(trc::location!())
                        .document_id(document_id)
                })?,
            ) {
                Ok(sieve) => {
                    // Store updated compiled sieve script
                    let sieve = Bincode::new(sieve);
                    let compiled_bytes = (&sieve).serialize();
                    let mut updated_sieve_bytes =
                        Vec::with_capacity(script_offset + compiled_bytes.len());
                    updated_sieve_bytes.extend_from_slice(&script_bytes[0..script_offset]);
                    updated_sieve_bytes.extend_from_slice(&compiled_bytes);

                    // Store updated blob
                    let mut new_blob_id = blob_id.clone();
                    new_blob_id.hash = self
                        .put_blob(account_id, &updated_sieve_bytes, false)
                        .await?
                        .hash;
                    let mut new_script_object = script_object.inner.clone();
                    new_script_object.set(Property::BlobId, new_blob_id.clone());

                    // Update script object
                    let mut batch = BatchBuilder::new();
                    batch
                        .with_account_id(account_id)
                        .with_collection(Collection::SieveScript)
                        .update_document(document_id)
                        .assert_value(Property::Value, &script_object)
                        .set(Property::Value, (&new_script_object).serialize())
                        .clear(BlobOp::Link {
                            hash: blob_id.hash.clone(),
                        })
                        .set(
                            BlobOp::Link {
                                hash: new_blob_id.hash,
                            },
                            Vec::new(),
                        );
                    self.store()
                        .write(batch.build())
                        .await
                        .caused_by(trc::location!())?;

                    Ok((sieve.inner, new_script_object))
                }
                Err(error) => Err(trc::StoreEvent::UnexpectedError
                    .caused_by(trc::location!())
                    .reason(error)
                    .details("Failed to compile Sieve script")),
            }
        }
    }
}

#[inline(always)]
pub fn is_valid_role(role: &str) -> bool {
    [
        "inbox",
        "trash",
        "spam",
        "junk",
        "drafts",
        "archive",
        "sent",
        "important",
    ]
    .contains(&role)
}

impl SeenIdHash {
    pub fn new(id: &str, expiry: u64) -> Self {
        let mut hasher = blake3::Hasher::new();
        hasher.update(id.as_bytes());
        SeenIdHash {
            hash: hasher.finalize().into(),
            expiry,
        }
    }
}

impl PartialOrd for SeenIdHash {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SeenIdHash {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.expiry.cmp(&other.expiry)
    }
}

impl std::hash::Hash for SeenIdHash {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.hash.hash(state);
    }
}

impl PartialEq for SeenIdHash {
    fn eq(&self, other: &Self) -> bool {
        self.hash == other.hash
    }
}

impl Eq for SeenIdHash {}

// SeenIds serializer
impl serde::Serialize for SeenIds {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut seq = serializer.serialize_seq((self.ids.len() * 2).into())?;
        for id in &self.ids {
            seq.serialize_element(&id.expiry)?;
            seq.serialize_element(&id.hash)?;
        }

        seq.end()
    }
}

impl<'de> serde::Deserialize<'de> for SeenIds {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_seq(SeenIdsVisitor)
    }
}

struct SeenIdsVisitor;

impl<'de> serde::de::Visitor<'de> for SeenIdsVisitor {
    type Value = SeenIds;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("invalid SeenIds")
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        let num_entries = seq.size_hint().unwrap_or(0) / 2;
        let mut seen_ids = SeenIds {
            ids: AHashSet::with_capacity(num_entries),
            has_changes: false,
        };
        let now = now();

        for _ in 0..num_entries {
            let expiry = seq
                .next_element::<u64>()?
                .ok_or_else(|| serde::de::Error::custom("Expected expiry."))?;
            if expiry > now {
                seen_ids.ids.insert(SeenIdHash {
                    hash: seq
                        .next_element()?
                        .ok_or_else(|| serde::de::Error::custom("Expected hash."))?,
                    expiry,
                });
            } else {
                seq.next_element::<[u8; 32]>()?
                    .ok_or_else(|| serde::de::Error::custom("Expected hash."))?;
                seen_ids.has_changes = true;
            }
        }

        Ok(seen_ids)
    }
}
