// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use fastcrypto::encoding::{self, Encoding};
use serde::{Deserialize, Serialize};

use crate::validation::ValidationError;

/// Response message for the `getSecretSharingPubkey` RPC method.
///
/// Returns the current Secret Sharing Public Key
#[derive(Serialize, Deserialize, Debug)]
pub struct GetSecretSharingPubkeyResponse {
    /// The current secrets public key (32 bytes, hex-encoded)
    pubkey: String,
}

impl GetSecretSharingPubkeyResponse {
    pub fn new(public_key: &[u8; 32]) -> Self {
        Self {
            pubkey: encoding::Hex::encode(public_key),
        }
    }

    pub fn get_public_key(&self) -> Result<[u8; 32], ValidationError> {
        let pubkey_bytes = encoding::Hex::decode(&self.pubkey)
            .map_err(|e| ValidationError::InvalidFormat(e.to_string()))?;
        // Convert to fixed-size array
        let len = pubkey_bytes.len();
        let pubkey_array: [u8; 32] = pubkey_bytes.try_into().map_err(|_| {
            ValidationError::InvalidFormat(format!(
                "Invalid public key length: expected 32 bytes, got {len}",
            ))
        })?;
        Ok(pubkey_array)
    }
}
