use alloy::primitives::Bytes;
use serde::{Deserialize, Serialize};

use crate::WasmProvider;

pub struct AggregatedPolicyDataWasm {
    pub data: Vec<PolicyDataWasm>,
    pub attestation: Bytes,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PolicyDataWasm {
    pub specifier: WasmProvider,
    pub data: serde_json::Value,
    pub timestamp: u64,
}

impl PolicyDataWasm {
    pub fn new(specifier: WasmProvider, data: serde_json::Value) -> Self {
        Self {
            specifier,
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            data,
        }
    }

    /// Convert to bytes for contract storage
    pub fn to_bytes(&self) -> Result<Bytes, serde_json::Error> {
        let json = serde_json::to_string(self)?;
        Ok(Bytes::from(json.into_bytes()))
    }

    /// Create from bytes
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        let json = std::str::from_utf8(bytes).map_err(|_| {
            serde_json::Error::io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid UTF-8 sequence",
            ))
        })?;
        serde_json::from_str(json)
    }
}
