// Copyright 2023 Salesforce, Inc. All rights reserved.
use std::convert::TryFrom;

use serde::Deserialize;

use crate::api::status::Status;
use crate::api::status::Status::ParseFailure;

#[derive(Debug, Deserialize)]
pub struct PolicyMetadata {
    #[serde(alias = "name")]
    policy_name: String,

    #[serde(alias = "namespace")]
    policy_namespace: String,
}

impl PolicyMetadata {
    pub fn policy_name(&self) -> &str {
        &self.policy_name
    }
    pub fn policy_namespace(&self) -> &str {
        &self.policy_namespace
    }
}

impl TryFrom<Vec<u8>> for PolicyMetadata {
    type Error = Status;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        let parsed: Self = serde_json::from_slice(value.as_ref()).map_err(|_| ParseFailure)?;
        if parsed.policy_name.is_empty() || parsed.policy_namespace.is_empty() {
            return Err(ParseFailure);
        }
        Ok(parsed)
    }
}
