//! Example: Request and verify a base credential
//!
//! This example demonstrates the basic flow for requesting and verifying
//! credentials using the LastID SDK.
//!
//! # Setup
//!
//! 1. Create a `lastid.toml` configuration file:
//!    ```toml
//!    idp_endpoint = "https://human.dev.lastid.co"
//!
//!    [polling]
//!    timeout_seconds = 120
//!    ```
//!
//! 2. Run the example: ```bash cargo run --example base_credential ```
//!
//! # What This Example Does
//!
//! 1. Initializes the SDK client with auto-discovered configuration
//! 2. Builds a type-safe credential policy
//! 3. Requests a credential from the IDP
//! 4. Polls for the user's response
//! 5. Verifies the returned presentation

use lastid_sdk::{BaseCredentialPolicy, ClientBuilder, LastIDError, PolicyBuilder, RequestStatus};

#[tokio::main]
async fn main() -> Result<(), LastIDError> {
    // Initialize tracing for logging (optional)
    #[cfg(feature = "tracing")]
    {
        use tracing_subscriber::EnvFilter;
        tracing_subscriber::fmt()
            .with_env_filter(
                EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
            )
            .init();
    }

    println!("=== LastID SDK: Base Credential Example ===\n");

    // Step 1: Initialize the client
    println!("Step 1: Initializing SDK client...");
    let client = ClientBuilder::new()
        .with_auto_config()
        .map_err(|e| {
            eprintln!("Hint: Create a lastid.toml file with your IDP configuration");
            e
        })?
        .build()?;

    println!(
        "  ✓ Client initialized with endpoint: {}",
        client.config().idp_endpoint
    );

    // Step 2: Build the credential policy
    println!("\nStep 2: Building credential policy...");
    let callback_url = "https://your-app.example.com/callback";
    let policy = BaseCredentialPolicy::new().with_callback(callback_url);

    println!("  ✓ Policy type: {}", policy.credential_type());
    println!("  ✓ Callback URL: {}", callback_url);

    // Step 3: Request the credential
    println!("\nStep 3: Requesting credential from IDP...");
    let response = client.request_credential(policy).await?;
    println!("  ✓ Request ID: {}", response.request_id);
    println!("  ✓ Request URI: {}", response.request_uri());
    println!("  ✓ Expires in: {}s", response.expires_in);

    // Step 4: Poll for completion
    println!("\nStep 4: Waiting for user response...");
    println!("  (User should scan QR code with the request_uri in the LastID app)");

    // poll_for_completion returns Err(LastIDError::Timeout) on timeout (FR-010)
    let status = match client.poll_for_completion(response.request_id()).await {
        Ok(status) => status,
        Err(LastIDError::Timeout(elapsed_seconds)) => {
            println!("\nStep 5: Processing result...");
            println!("  ✗ Polling timed out after {} seconds", elapsed_seconds);
            println!("    Hint: Increase polling.timeout_seconds in your config");
            return Ok(());
        }
        Err(e) => return Err(e),
    };

    // Step 5: Process the result
    println!("\nStep 5: Processing result...");
    match status {
        RequestStatus::Fulfilled {
            presentation,
            fulfilled_at,
            ..
        } => {
            println!("  ✓ Credential received at: {}", fulfilled_at);

            // Verify the presentation
            println!("\nStep 6: Verifying presentation...");
            let verified = client.verify_presentation(&presentation).await?;

            println!("  ✓ Subject DID: {}", verified.subject_did);
            println!("  ✓ Issuer DID: {}", verified.issuer_did);
            println!("  ✓ Credential Type: {}", verified.credential_type);
            println!("  ✓ Issuer Status: {:?}", verified.issuer_status);
            println!("  ✓ Issued At: {}", verified.issued_at);
            println!("  ✓ Expires At: {}", verified.expires_at);

            // Check if the issuer is trusted
            if verified.issuer_status.is_valid() {
                println!("\n SUCCESS: Credential verified from trusted issuer!");
            } else {
                println!("\n WARNING: Issuer status is {:?}", verified.issuer_status);
            }
        }
        RequestStatus::Denied {
            reason, denied_at, ..
        } => {
            println!("  ✗ Request denied at {}: {}", denied_at, reason);
        }
        RequestStatus::Expired { expired_at, .. } => {
            println!("  ✗ Request expired at: {}", expired_at);
        }
        RequestStatus::NotFound { message, .. } => {
            println!("  ✗ Request not found: {}", message);
            println!("    The request may have been deleted or never existed");
        }
        RequestStatus::Pending { .. } => {
            // This shouldn't happen after poll_for_completion
            println!("  ? Request still pending (unexpected)");
        }
        _ => {
            // Handle future variants that may be added
            println!("  ? Unknown status (SDK may need updating)");
        }
    }

    Ok(())
}
