//! Parsed Persona credential type.

use serde::{Deserialize, Serialize};

use crate::error::LastIDError;
use crate::types::VerifiedCredential;

/// Parsed `LastID.Persona` credential with typed fields.
///
/// # Example
///
/// ```rust,ignore
/// use lastid_sdk::types::parsed::ParsedPersona;
///
/// let persona = ParsedPersona::try_from(&credential)?;
/// if let Some(name) = &persona.display_name {
///     println!("Name: {}", name);
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct ParsedPersona {
    /// Display name.
    pub display_name: Option<String>,
    /// Email address.
    pub email: Option<String>,
    /// Phone number.
    pub phone: Option<String>,
    /// Company/employer name.
    pub company: Option<String>,
    /// Job title.
    pub job_title: Option<String>,
    /// Avatar URL.
    pub avatar_url: Option<String>,
    /// Website URL.
    pub website: Option<String>,
    /// Location.
    pub location: Option<String>,
    /// Visibility setting.
    pub visibility: Option<String>,
}

impl TryFrom<&VerifiedCredential> for ParsedPersona {
    type Error = LastIDError;

    fn try_from(cred: &VerifiedCredential) -> Result<Self, Self::Error> {
        if cred.credential_type != "LastID.Persona" {
            return Err(LastIDError::invalid_credential(format!(
                "Expected LastID.Persona, got {}",
                cred.credential_type
            )));
        }

        Ok(Self {
            display_name: cred.get_claim_str("display_name").map(String::from),
            email: cred.get_claim_str("email").map(String::from),
            phone: cred.get_claim_str("phone").map(String::from),
            company: cred.get_claim_str("company").map(String::from),
            job_title: cred.get_claim_str("job_title").map(String::from),
            avatar_url: cred.get_claim_str("avatar_url").map(String::from),
            website: cred.get_claim_str("website").map(String::from),
            location: cred.get_claim_str("location").map(String::from),
            visibility: cred.get_claim_str("visibility").map(String::from),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::trust_registry::IssuerStatus;
    use chrono::Utc;

    fn test_credential(cred_type: &str, claims: serde_json::Value) -> VerifiedCredential {
        VerifiedCredential {
            subject_did: "did:lastid:user123".into(),
            issuer_did: "did:lastid:issuer456".into(),
            credential_type: cred_type.into(),
            claims,
            issued_at: Utc::now(),
            expires_at: Utc::now() + chrono::Duration::hours(24),
            issuer_status: IssuerStatus::Authorized,
            signature_verified: true,
        }
    }

    #[test]
    fn test_parse_persona() {
        let cred = test_credential(
            "LastID.Persona",
            serde_json::json!({
                "display_name": "John Doe",
                "email": "john@example.com",
                "company": "Acme Corp"
            }),
        );

        let persona = ParsedPersona::try_from(&cred).unwrap();
        assert_eq!(persona.display_name, Some("John Doe".to_string()));
        assert_eq!(persona.email, Some("john@example.com".to_string()));
        assert_eq!(persona.company, Some("Acme Corp".to_string()));
        assert!(persona.phone.is_none());
    }

    #[test]
    fn test_parse_persona_wrong_type() {
        let cred = test_credential("LastID.Employment", serde_json::json!({}));

        let result = ParsedPersona::try_from(&cred);
        assert!(result.is_err());
    }
}
