//! Parsed `VerifiedEmail` credential type.

use serde::{Deserialize, Serialize};

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

/// Parsed `LastID.VerifiedEmail` credential with typed fields.
///
/// # Required Fields
///
/// Unlike other parsed types, `email` is a required field for `VerifiedEmail`
/// credentials since verification wouldn't exist without it.
///
/// # Example
///
/// ```rust,ignore
/// use lastid_sdk::types::parsed::ParsedVerifiedEmail;
///
/// let email = ParsedVerifiedEmail::try_from(&credential)?;
/// println!("Verified email: {}", email.email);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ParsedVerifiedEmail {
    /// Verified email address (required).
    pub email: String,
    /// Timestamp when email was verified (Unix epoch seconds).
    pub verified_at: Option<i64>,
    /// Verification method (e.g., "oauth", "`email_link`").
    pub verification_method: Option<String>,
    /// Verification provider (e.g., "google", "lastid").
    pub provider: Option<String>,
}

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

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

        let email = cred
            .get_claim_str("email")
            .ok_or_else(|| LastIDError::invalid_credential("Missing required field: email"))?
            .to_string();

        Ok(Self {
            email,
            verified_at: cred.get_claim_i64("verified_at"),
            verification_method: cred.get_claim_str("verification_method").map(String::from),
            provider: cred.get_claim_str("provider").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_verified_email() {
        let cred = test_credential(
            "LastID.VerifiedEmail",
            serde_json::json!({
                "email": "user@example.com",
                "provider": "google",
                "verification_method": "oauth"
            }),
        );

        let email = ParsedVerifiedEmail::try_from(&cred).unwrap();
        assert_eq!(email.email, "user@example.com");
        assert_eq!(email.provider, Some("google".to_string()));
        assert_eq!(email.verification_method, Some("oauth".to_string()));
    }

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

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

    #[test]
    fn test_parse_verified_email_wrong_type() {
        let cred = test_credential(
            "LastID.Persona",
            serde_json::json!({"email": "user@example.com"}),
        );

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