//! Example: Multi-Credential Chain Handling (FR-029)
//!
//! Demonstrates using VerifiedResponse to handle presentations with multiple
//! credentials and traverse credential chains.
//!
//! # Use Case
//!
//! When a user presents multiple credentials (e.g., Base → Persona → Employment),
//! the VerifiedResponse provides:
//! 1. Access to all credentials in the chain
//! 2. Lookup by credential type
//! 3. Chain traversal from root to leaf
//! 4. Shared device attestation/security context
//!
//! # Running
//!
//! ```bash
//! cargo run --example multi_credential_chain --features persona-policy,employment-policy
//! ```

use chrono::Utc;
use lastid_sdk::{
    LastIDError,
    trust_registry::IssuerStatus,
    types::{
        DeviceAttestation, DeviceSecurity, VerifiedCredential, VerifiedResponse,
        parsed::{ParsedEmployment, ParsedPersona},
    },
};

fn main() -> Result<(), LastIDError> {
    println!("=== Multi-Credential Chain Handling Example ===\n");

    // Simulated multi-credential response (in production, from verify_presentation())
    let base_credential = VerifiedCredential {
        subject_did: "did:lastid:user123".into(),
        issuer_did: "did:lastid:root".into(),
        credential_type: "LastID.Base".into(),
        claims: serde_json::json!({}),
        issued_at: Utc::now(),
        expires_at: Utc::now() + chrono::Duration::hours(24),
        issuer_status: IssuerStatus::Authorized,
        signature_verified: true,
    };

    let persona_credential = VerifiedCredential {
        subject_did: "did:lastid:user123".into(),
        issuer_did: "did:lastid:issuer456".into(),
        credential_type: "LastID.Persona".into(),
        claims: serde_json::json!({
            "display_name": "John Doe",
            "email": "john@acme-corp.com",
            "company": "Acme Corp"
        }),
        issued_at: Utc::now(),
        expires_at: Utc::now() + chrono::Duration::hours(24),
        issuer_status: IssuerStatus::Authorized,
        signature_verified: true,
    };

    let employment_credential = VerifiedCredential {
        subject_did: "did:lastid:user123".into(),
        issuer_did: "did:lastid:acme-hr".into(),
        credential_type: "LastID.Employment".into(),
        claims: serde_json::json!({
            "company": "Acme Corp",
            "title": "Senior Engineer",
            "department": "Engineering",
            "is_current": true
        }),
        issued_at: Utc::now(),
        expires_at: Utc::now() + chrono::Duration::hours(24),
        issuer_status: IssuerStatus::Authorized,
        signature_verified: true,
    };

    // Create VerifiedResponse with device context
    let device_attestation = DeviceAttestation {
        has_secure_element: true,
        has_tee: true,
        integrity_status: "pass".to_string(),
        ..Default::default()
    };

    let device_security = DeviceSecurity {
        security_level: "high".to_string(),
        biometric_used: true,
        platform: "ios".to_string(),
    };

    let response = VerifiedResponse::new(vec![
        base_credential,
        persona_credential,
        employment_credential,
    ])
    .with_device_attestation(device_attestation)
    .with_device_security(device_security);

    // Example 1: Iterate over all credentials
    println!("1. All Credentials in Response");
    for cred in response.credentials() {
        println!("   - {}", cred.credential_type);
    }
    println!("   Total: {} credentials", response.len());
    println!();

    // Example 2: Lookup by credential type
    println!("2. Lookup by Credential Type");
    if let Some(persona) = response.credential_by_type("LastID.Persona") {
        println!("   Found Persona credential");
        println!("   Subject: {}", persona.subject_did);
        println!("   Display Name: {:?}", persona.display_name());
    }
    println!();

    // Example 3: Credential chain traversal
    println!("3. Credential Chain (Root → Leaf)");
    for (i, cred) in response.credential_chain().iter().enumerate() {
        let arrow = if i > 0 { " → " } else { "" };
        print!("{}{}", arrow, cred.credential_type);
    }
    println!("\n");

    // Example 4: Primary (leaf) credential
    println!("4. Primary Credential");
    if let Some(primary) = response.primary_credential() {
        println!("   Type: {}", primary.credential_type);
        println!("   (This is the most specific credential in the chain)");
    }
    println!();

    // Example 5: Device attestation (shared across all credentials)
    println!("5. Device Attestation (Shared)");
    if let Some(attestation) = response.device_attestation() {
        println!("   has_secure_element: {}", attestation.has_secure_element);
        println!("   integrity_status: {}", attestation.integrity_status);
        println!("   is_high_security(): {}", attestation.is_high_security());
    }
    println!();

    // Example 6: Device security (shared across all credentials)
    println!("6. Device Security (Shared)");
    if let Some(security) = response.device_security() {
        println!("   security_level: {}", security.security_level);
        println!("   biometric_used: {}", security.biometric_used);
        println!("   platform: {}", security.platform);
    }
    println!();

    // Example 7: Parse specific credentials into typed structs
    println!("7. Parse Credentials into Typed Structs");
    if let Some(persona_cred) = response.credential_by_type("LastID.Persona") {
        let parsed = ParsedPersona::try_from(persona_cred)?;
        println!("   ParsedPersona:");
        println!("     display_name: {:?}", parsed.display_name);
        println!("     email: {:?}", parsed.email);
    }

    if let Some(employment_cred) = response.credential_by_type("LastID.Employment") {
        let parsed = ParsedEmployment::try_from(employment_cred)?;
        println!("   ParsedEmployment:");
        println!("     company: {:?}", parsed.company);
        println!("     title: {:?}", parsed.title);
    }
    println!();

    // Example 8: Validation checks
    println!("8. Response Validation");
    println!(
        "   all_signatures_verified(): {}",
        response.all_signatures_verified()
    );
    println!(
        "   has_expired_credential(): {}",
        response.has_expired_credential()
    );

    println!("\n=== Multi-Credential Chain Example Complete ===");
    Ok(())
}
