use ex3_timestamp::TimeInNs;
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;

use ex3_node_error::OtherError;
use ex3_serde::bincode;

use crate::balance_changed::BalanceChanged;
use crate::transaction::EncodedTransaction;
use crate::{AssetId, PackageId, WalletRegisterId};

#[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq)]
pub struct TransactionPackage {
    pub id: PackageId,
    pub pack: bool,
    pub txs: Vec<EncodedTransaction>,
    // TODO: remove in the future
    pub balance_changed_records: Vec<(WalletRegisterId, Vec<(AssetId, BalanceChanged)>)>,
    pub timestamp: TimeInNs,
}

impl TryFrom<&[u8]> for TransactionPackage {
    type Error = OtherError;
    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        bincode::deserialize(value)
            .map_err(|e| OtherError::new(format!("TransactionPackage deserialize error: {}", e)))
    }
}

#[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(transparent)]
pub struct EncodeTransactionPackage(pub ByteBuf);

impl From<TransactionPackage> for EncodeTransactionPackage {
    fn from(tx_package: TransactionPackage) -> Self {
        let bytes = bincode::serialize(&tx_package).unwrap();
        EncodeTransactionPackage(ByteBuf::from(bytes))
    }
}

impl From<EncodeTransactionPackage> for TransactionPackage {
    fn from(tx_package: EncodeTransactionPackage) -> Self {
        TransactionPackage::try_from(tx_package.0.as_ref()).unwrap()
    }
}
