use candid::Deserialize;
use ex3_serde::bincode::{deserialize, serialize};
use serde::Serialize;
use serde_bytes::ByteBuf;

use ex3_node_error::OtherError;

use crate::PublicKey;

#[derive(Clone, Deserialize, Serialize, Debug, Eq, PartialEq)]
pub struct SecretPublicKeyPocket {
    pub main_secret_pub_key: ByteBuf,
    pub api_secret_pub_keys: Vec<ByteBuf>,
}

impl SecretPublicKeyPocket {
    pub fn encode(&self) -> Vec<u8> {
        serialize(&(&self.main_secret_pub_key, &self.api_secret_pub_keys)).unwrap()
    }

    pub fn decode(bytes: &[u8]) -> Result<Self, String> {
        let (main_secret_pub_key, api_secret_pub_keys) = deserialize(bytes).map_err(|e| {
            format!(
                "Failed to deserialize SecretPublicKeyPocket: {}",
                e.to_string()
            )
        })?;
        Ok(Self {
            main_secret_pub_key,
            api_secret_pub_keys,
        })
    }

    pub fn exists(&self, secret_pub_key: PublicKey) -> bool {
        self.main_secret_pub_key == secret_pub_key
            || self
                .api_secret_pub_keys
                .iter()
                .any(|key| key == &secret_pub_key)
    }
}

impl TryFrom<&[u8]> for SecretPublicKeyPocket {
    type Error = OtherError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        let (main_secret_pub_key, api_secret_pub_keys) = deserialize(value).map_err(|e| {
            OtherError::new(format!(
                "Failed to deserialize SecretPublicKeyPocket: {}",
                e
            ))
        })?;
        Ok(Self {
            main_secret_pub_key,
            api_secret_pub_keys,
        })
    }
}
