//! Parsed Employment credential type.

use serde::{Deserialize, Serialize};

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

/// Parsed `LastID.Employment` credential with typed fields.
///
/// # Example
///
/// ```rust,ignore
/// use lastid_sdk::types::parsed::ParsedEmployment;
///
/// let employment = ParsedEmployment::try_from(&credential)?;
/// if let Some(company) = &employment.company {
///     println!("Company: {}", company);
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct ParsedEmployment {
    /// Company/employer name.
    pub company: Option<String>,
    /// Job title.
    pub title: Option<String>,
    /// Department.
    pub department: Option<String>,
    /// Employment start date.
    pub start_date: Option<String>,
    /// Employment end date.
    pub end_date: Option<String>,
    /// Whether this is current employment.
    pub is_current: Option<bool>,
    /// Job responsibilities.
    pub responsibilities: Option<String>,
}

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

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

        Ok(Self {
            company: cred.get_claim_str("company").map(String::from),
            title: cred.get_claim_str("title").map(String::from),
            department: cred.get_claim_str("department").map(String::from),
            start_date: cred.get_claim_str("start_date").map(String::from),
            end_date: cred.get_claim_str("end_date").map(String::from),
            is_current: cred.get_claim_bool("is_current"),
            responsibilities: cred.get_claim_str("responsibilities").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_employment() {
        let cred = test_credential(
            "LastID.Employment",
            serde_json::json!({
                "company": "Acme Corp",
                "title": "Engineer",
                "department": "R&D",
                "is_current": true
            }),
        );

        let employment = ParsedEmployment::try_from(&cred).unwrap();
        assert_eq!(employment.company, Some("Acme Corp".to_string()));
        assert_eq!(employment.title, Some("Engineer".to_string()));
        assert_eq!(employment.department, Some("R&D".to_string()));
        assert_eq!(employment.is_current, Some(true));
    }

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

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